标签:2.4 file ati tor 自身 rac tps mini public
java图片压缩,有时由于图片自身的原因,如透明的PNG图、改alpha通道或四色图等。
压缩完了,会出现图片变色的情况。
如:
原图
压缩完:
尝试了很多方法,如JDK原生的方式及第三方组件java-image-scaling或thumbnailator都不解决问题。
后来采用阿里的SimpleImage解决。记录一下
SimpleImage github地址:https://github.com/alibaba/simpleimage
依赖jar:commons-io-2.4.jar
commons-lang.jar
commons-logging-1.1.1.jar
jai_codec-1.1.3.jar
jai_core-1.1.3.jar
测试代码:
public static void main(String[] args) { // 原图 File in = new File( "C:/Users/Administrator/Desktop/img/20170916/attachment_15055700026790.jpeg"); // 目的图 File out = new File( "C:/Users/Administrator/Desktop/img/20170916/attachment_15055700026790a.jpeg"); FileInputStream input = null; FileOutputStream outStream = null; WriteRender wr = null; try { BufferedImage image = ImageIO.read(in); ScaleParameter scaleParam = new ScaleParameter(image.getWidth(), image.getHeight()); // 将图像缩略到1024x1024以内,不足1024x1024则不做任何处理 input = new FileInputStream(in); outStream = new FileOutputStream(out); ImageRender rr = new ReadRender(input); ImageRender sr = new ScaleRender(rr, scaleParam); wr = new WriteRender(sr, outStream); wr.render(); // 触发图像处理 } catch (Exception e) { e.printStackTrace(); } finally { if (null != input) { try { input.close(); } catch (Exception e) { e.printStackTrace(); } } if (null != outStream) { try { outStream.close(); } catch (Exception e) { e.printStackTrace(); } } if (wr != null) { try { wr.dispose(); // 释放simpleImage的内部资源 } catch (SimpleImageException ignore) { // skip ... } } } }
引入的pom文件代码:
<dependency> <groupId>com.alibaba</groupId> <artifactId>simpleimage</artifactId> <version>1.2.3</version> </dependency>
标签:2.4 file ati tor 自身 rac tps mini public
原文地址:http://www.cnblogs.com/ncyhl/p/7554737.html