使用第三方jar
net.coobird thumbnailator0.4.15 com.twelvemonkeys.imageio imageio-jpeg3.6
代码
public static String getFileBase64StrByFilePath(String filePath){
if(StringUtils.isBlank(filePath)){
return null;
}
InputStream in = null;
String base64 = null;
//读取图片字节数组
try {
in = new FileInputStream(filePath);
byte[] data = new byte[in.available()];
in.read(data);
in.close();
base64 = getFileBase64StrByBytes(data);
} catch (Throwable t) {
t.printStackTrace();
}finally {
IoUtil.close(in);
}
return base64;
}
public static String getFileBase64StrByBytes(byte[] data){
if(data == null){
return null;
}
String base64 = null;
//读取图片字节数组
try {
BASE64Encoder encoder = new BASE64Encoder();
base64 = encoder.encode(data);
} catch (Throwable t) {
t.printStackTrace();
}
return base64;
}
public static byte[] compressImage(String path, int fileMin) {
byte[] smallImage = null;
try {
long desFileSize = 1024;
File imgFile = new File(path);
long fileSize = imgFile.length();
//判断大小,如果小于指定大小,不压缩,如果大于等于指定大小,压缩
if(fileSize > (desFileSize * fileMin)){
Double accuracy = 0.8;
ByteArrayOutputStream out = new ByteArrayOutputStream();
//计算宽高
BufferedImage bim = ImageIO.read(imgFile);
int imgWidth = bim.getWidth();
int imgHeight = bim.getHeight();
int desWidth = NumberUtil.multiply(new BigDecimal(imgWidth), new BigDecimal(accuracy)).intValue();
int desHeight = NumberUtil.multiply(new BigDecimal(imgHeight), new BigDecimal(accuracy)).intValue();
Thumbnails.of(path).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(out);
smallImage = out.toByteArray();
}else{
FileInputStream in = new FileInputStream(imgFile);
smallImage = new byte[in.available()];
in.read(smallImage);
IoUtil.close(in);
}
} catch (Throwable t) {
t.printStackTrace();
}
return smallImage;
}



