图片压缩

#废话不说直接上代码

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 * 图片压缩
 * 
 * @author KEVIN LUAN
 *
 */
public class CompressImageUtils {

	public static void main(String[] args) throws IOException {
		String src = "/Users/kevin/Downloads/img_src.jpg";
		scaleImage(src);
		compress(src);

	}

	// # >0.75 high quality ,0.5 medium quality ,0.25 low quality
	// QualityParam=0.95
	private static float QUALITY = 0.9f;
	/**
	 * 在压缩后的图片名称价格质量标示
	 */
	private static String APPEND_QUALITY_NAME = "_9";

	public static void compress(String src) throws IOException {
		File outFile = new File(buildNewName(src));
		BufferedImage bufferedImage = ImageIO.read(new File(src));
		JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(bufferedImage);
		jep.setQuality(QUALITY, false);
		FileOutputStream out = new FileOutputStream(outFile); // 输出到文件流
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out, jep);
		encoder.encode(bufferedImage);
		out.close();
	}

	public static void scaleImage(String srcFile) throws IOException {
		File file = new File(srcFile);
		BufferedImage src = ImageIO.read(file);
		int width = src.getWidth();
		int height = src.getHeight();
		BufferedImage _image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		_image.getGraphics().drawImage(src, 0, 0, width, height, null); // 绘制缩小后的图
		Iterator<?> writers = ImageIO.getImageWritersBySuffix("jpg");
		ImageWriter writer = (ImageWriter) writers.next();
		ImageWriteParam param = writer.getDefaultWriteParam();
		param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		param.setCompressionQuality(QUALITY);
		ImageOutputStream outStream = ImageIO.createImageOutputStream(new File(buildNewName(srcFile)));
		writer.setOutput(outStream);
		IIOImage iioImage = new IIOImage(src, null, (IIOMetadata) null);
		writer.write((IIOMetadata) null, iioImage, param);
		outStream.flush();
		outStream.close();
	}

	private static String buildNewName(String src) {
		if (src != null && src.indexOf(".") != -1) {
			int index = src.lastIndexOf(".");
			return src.substring(0, index) + APPEND_QUALITY_NAME + src.substring(index);
		}
		return src + APPEND_QUALITY_NAME;
	}

}


你可能感兴趣的:(图片)