需求:
大于2mb的图片需要压缩到2mb以下,且不改变原图的尺寸。
(推荐教程:java入门教程)
引入依赖:
<dependency> <groupid>net.coobird</groupid> <artifactid>thumbnailator</artifactid> <version>0.4.8</version> </dependency>
附件实体类:
@builder@noargsconstructor@allargsconstructor@datapublic class fileco { /** * 附件字节流 */ private byte[] filecontent; /** * 附件oid */ private uuid attachmentoid;}
(视频教程推荐:java视频教程)
图片实体类:
@builder@noargsconstructor@allargsconstructor@datapublic class imageinfo { /** * 图片字节流 */ private byte[] imagebytes; /** * 图片是否进行压缩 */ private boolean compressflag; /** * 图片宽度 */ private integer width; /** * 图片高度 */ private integer height;}
图片压缩工具类:
@slf4jpublic class imageutils { /** * 合法图片大小为2mb */ private static final long legal_image_size = 1024 * 2l; /** * 图片压缩 当图片大小大于2mb进行等比例压缩 * 不修改图片尺寸进行压缩 * * @param fileco * @return */ public static imageinfo compressimageforscale(fileco fileco) throws ioexception { byte[] imagebytes = fileco.getfilecontent(); uuid attachmentoid = fileco.getattachmentoid(); try { bufferedimage sourceimage = imageio.read(new bytearrayinputstream(imagebytes)); //高度 int height = sourceimage.getheight(); //宽度 int width = sourceimage.getwidth(); if (imagebytes.length <= 0 || imagebytes.length < legal_image_size * 1024) { return imageinfo.builder() .imagebytes(imagebytes) .width(width) .height(height) .compressflag(false) .build(); } long srcsize = imagebytes.length; double accuracy = getaccuracy(srcsize / 1024); while (imagebytes.length > legal_image_size * 1024) { bytearrayinputstream inputstream = new bytearrayinputstream(imagebytes); bytearrayoutputstream outputstream = new bytearrayoutputstream(imagebytes.length); thumbnails.of(inputstream) .scale(1f) .outputquality(accuracy) .tooutputstream(outputstream); imagebytes = outputstream.tobytearray(); } log.info("【图片压缩】附件oid={} | 图片原大小={}kb | 压缩后大小={}kb", attachmentoid, srcsize / 1024, imagebytes.length / 1024); return imageinfo.builder() .imagebytes(imagebytes) .width(width) .height(height) .compressflag(true) .build(); } catch (exception e) { log.error("【图片压缩】msg=图片压缩失败!", e); throw e; } } /** * 计算压缩精度 * * @param size * @return */ private static double getaccuracy(long size) { double accuracy; //图片大小小于4m,压缩精度为0.44;否则精度为0.4 if (size <= 2048 * 2) { accuracy = 0.44; } else { accuracy = 0.4; } return accuracy; }}
以上就是java实现压缩图片且不改变原图尺寸的详细内容。