package com.function; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; /* * 这是一个压缩图片的实现类 */ public class Tools_CompressPictures { public void compressPicture(String srcImage,String tarImage) { File srcImageFile = new File(srcImage); File tarImageFile = new File(tarImage); // 生成图片转化对象 AffineTransform transform = new AffineTransform(); // 通过缓存读入缓存对象 BufferedImage image = null; try { image = ImageIO.read(srcImageFile); } catch (IOException e) { e.printStackTrace(); } int imageWidth = image.getWidth();//原图片的高度 int imageHeight = image.getHeight();//原图片的宽度 int changeWidth = 640;//压缩后图片的高度 int changeHeight = 480;//压缩后图片的宽度 double scaleWidth = 0;// 定义小图片和原图片比例 double scaleHeight = 0; scaleWidth = (double) changeWidth / (double) imageWidth; scaleHeight = (double) changeHeight / (double) imageHeight; // 生成转换比例 transform.setToScale(scaleWidth, scaleHeight); // 生成转换操作对象 AffineTransformOp transOp = new AffineTransformOp(transform, null); //生成压缩图片缓冲对象 BufferedImage basll = new BufferedImage(changeWidth, changeHeight, BufferedImage.TYPE_3BYTE_BGR); //生成缩小图片 transOp.filter(image, basll); try { //输出缩小图片 ImageIO.write(basll, "jpg",tarImageFile); } catch (IOException e) { e.printStackTrace(); } } }