使用Thumbnails进行图片压缩异常处理。
需要用到的对象和参数
MultipartFile file;//需要进行压缩的图片文件
int width;//压缩后图片的宽度
int height;//压缩后图片的高度
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//接收压缩后输出的字节流
原方法是通过获取文件字节输入流,然后进行压缩:
InputStream fileInputStream =file.getInputStream();//获取文件的字节输入流
Thumbnails.of(fileInputStream).
size(width, height).keepAspectRatio(false).toOutputStream(outputStream);//进行压缩
使用原方法对某些类型图片进行压缩时,会报找不到合适的图片阅读器异常:net.coobird.thumbnailator.tasks.UnsupportedFormatException: No suitable ImageReader found for source data.
解决办法是,先获取文件字节数组,然后转换成为ByteArrayInputStream字节输入流,再进行压缩:
byte[] bytes =file.getBytes();//获取文件的字节数组
Thumbnails.of(new ByteArrayInputStream(bytes))//把字节数组转换成为字节输入流,然后进行压缩
.size(width, height).keepAspectRatio(false).toOutputStream(outputStream);