首先大概了解一下base64与图片压缩
Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),
然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,
转换后的字符串理论上将要比原来的长1/3。(空间占用约为原来的1.333倍)。
对于图片转为base64再转为byte数组,最好不要用java.util包下的Base64类,可能会出现报错,
改用org.apache.commons.codec.binary包下的Base64工具类。
经过实测使用Thumbnails去压缩无损的png格式并且压缩后格式不变的情况下,图片会越压越大,
而压缩有损的jpg格式并且压缩后依然是jpg,图片空间占用会大幅减小。
若想要png也能压小,目前我采用的是统一转换为jpg格式压缩。
java代码如下
//本地图片转为base64
public static String getPhotoBase64() throws IOException {
String PHOTOBASE64 = null;
byte[] bytes = null;
BufferedInputStream bufferedInputStream = new BufferedInputStream(
new FileInputStream(new File("D:\\image_before.png")));//选取自己的图片
bytes = new byte[bufferedInputStream.available()];
bufferedInputStream.read(bytes);
bufferedInputStream.close();
PHOTOBASE64 = Base64.encodeBase64String(bytes);
return PHOTOBASE64;
}
//base64转为inputStream
public static InputStream base64ToInputStream(String base64Stream){
byte[] bytes = Base64.decodeBase64(base64Stream);
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
return stream;
}
//outputStream转为base64
public static String outputStreamToBase64 (OutputStream outputStream){
byte[] bytes = ((ByteArrayOutputStream)outputStream).toByteArray();
String PHOTOBASE64 = Base64.encodeBase64String(bytes);
return PHOTOBASE64;
}
//base64生成图片
public static void generateImage(String imgStr) throws IOException {
byte[] bytes = Base64.decodeBase64(imgStr);
String imgPath = "D:\\image_after.jpg";
OutputStream outputStream = new FileOutputStream(imgPath);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
//图片压缩
public static void main(String[] args) throws IOException {
double a = 1.0;//压缩后的图片大小
double b = 0.8;//压缩后的图片质量
String inPHOTOBASE64 = getPhotoBase64();
System.out.println(inPHOTOBASE64.length()/1024 + "kb");
InputStream inputStream = base64ToInputStream(inPHOTOBASE64);
OutputStream outputStream = new ByteArrayOutputStream();
Thumbnails.of(inputStream).scale(a).outputQuality(b).
outputFormat("jpg").toOutputStream(outputStream);
String outPHOTOBASE64 = outputStreamToBase64(outputStream);
System.out.println(outPHOTOBASE64.length()/1024 + "kb");
generateImage(outPHOTOBASE64);
}
压缩效果
资源管理器看到的图片大小
控制台输出的字符串大小,可以看到控制台输出的base64串大小差不多为图片大小的1.333倍,与理论值符合.