项目中有个要求,对上传服务器的图片大小进行判断,大于500 k的图片要进行压缩处理,让其小于500 k后在上传。
可以通过java api的ImageIO实现图片压缩,但是看了网上的博客普遍都说虫子比较多,会有伯父内存溢出的现象。
缩略图插件是谷歌的插件,能指定不同的参数进行压缩操作。
比如:宽高(大小),缩放(规模),制定质量比(outputQuality)等。
插件使用的jar包为:
thumbnailator-0.4.8.jar 引用>
代码如下:
/* * * * @param srcPath原图片地址 * @param desPath目标图片地址 * @param desFileSize指定图片大小,单位kb * @param精度精度,递归压缩的比率,建议小于0.9 * @return */srcPath commpressPicForScale公共静态字符串(字符串,字符串desPath, 长desFileSize,双精度){ 尝试{ 文件srcFile=新文件(srcPath); 长srcFilesize=srcFile.length (); system . out。println(“原图片:“+ srcPath +”,大小:“+ srcFilesize/1024 +“知识库”);//递归压缩,直到目标文件大小小于desFileSize commpressPicCycle (desPath desFileSize、准确性); 文件desFile=新文件(desPath); system . out。println(“目标图片:“+ desPath +”,大小”+ desFile.length()/1024 +“知识库”); System.out.println(“图片压缩完成!”); }捕捉(异常e) { e.printStackTrace (); } 返回desPath; } 公共静态孔隙commpressPicCycle(字符串desPath、长desFileSize 双精度)抛出IOException { 文件imgFile=新文件(desPath); 长文件大?imgFile.length ();//判断大小,如果小于500 k,不压缩,如果大于等于500 k,压缩 如果(文件大小& lt;=desFileSize * 500) { 返回; }//计算宽高 BufferedImage bim=ImageIO.read (imgFile); int imgWidth=bim.getWidth (); int imgHeight=bim.getHeight (); int desWidth=new BigDecimal (imgWidth) .multiply ( 新BigDecimal(准确性)).intValue (); int desHeight=new BigDecimal (imgHeight) .multiply ( 新BigDecimal(准确性)).intValue (); Thumbnails.of (desPath)。大小(desWidth desHeight) .outputQuality(精度).toFile (desPath);//如果不满足要求,递归直至满足小于1米的要求 commpressPicCycle (desPath desFileSize、准确性); }然后压缩图片大小:
commpressPicForScale (filePath filePath 500, 0.8);压缩完成:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
使用缩略图实现图片指定大小压缩