解决java 图片压缩图片图片变色问题


最近有人遇到在处理在用Java进行图片压缩的时候,压缩后图片的背景色发生了变色,如图所示:

压缩前:

压缩后:


经查阅相关资料后发现可以用阿里巴巴的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

SimpleImage github地址:https://github.com/alibaba/simpleimage

相关jar包下载:http://download.csdn.net/detail/asd1231510/8911263

测试代码:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.io.IOUtils;
import com.alibaba.simpleimage.ImageRender;
import com.alibaba.simpleimage.SimpleImageException;
import com.alibaba.simpleimage.render.ReadRender;
import com.alibaba.simpleimage.render.ScaleParameter;
import com.alibaba.simpleimage.render.ScaleRender;
import com.alibaba.simpleimage.render.WriteRender;
 
public class Example {
 
    public static void main(String[] args) { 
        File in = new File("E:/20111014111307895.jpg");      //原图片
        File out = new File("E:/testImage.jpg");       //目的图片
        ScaleParameter scaleParam = new ScaleParameter(400, 400);  //将图像缩略到1024x1024以内,不足1024x1024则不做任何处理
         
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        WriteRender wr = null;
        try {
            inStream = new FileInputStream(in);
            outStream = new FileOutputStream(out);
            ImageRender rr = new ReadRender(inStream);
            ImageRender sr = new ScaleRender(rr, scaleParam);
            wr = new WriteRender(sr, outStream);
         
            wr.render();                            //触发图像处理
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inStream);         //图片文件输入输出流必须记得关闭
            IOUtils.closeQuietly(outStream);
            if (wr != null) {
                try {
                    wr.dispose();                   //释放simpleImage的内部资源
                } catch (SimpleImageException ignore) {
                    // skip ... 
                }
            }
        }
    }
}

运行测试代码后结果如图所示:

压缩前:800*407

压缩后:400*400