java按像素压缩,生成压缩图片。

2/22/2017来源:ASP.NET技巧人气:1985

package httPReq.guide; 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; /** * @author 作者yangjing: 图片压缩 * @date 创建时间:2017-2-17 下午6:42:05 */ public class imageTransformer { public static void main(String[] args) { //源图片文件 File srcImage = new File("G:/32/2015101713.jpg"); //目的图片文件 File tarImage = new File("G:/32/2015101713_720_720.jpg"); // 生成图片转化对象 AffineTransform transform = new AffineTransform(); // 通过缓存读入缓存对象 BufferedImage image = null; try { image = ImageIO.read(srcImage); } catch (IOException e) { e.printStackTrace(); } int maxPixel = 720;//转换的像素 int imageWidth = image.getWidth();//原图片的高度 int imageHeight = image.getHeight();//原图片的宽度 int changeWidth = 0;//压缩后图片的高度 int changeHeight = 0;//压缩后图片的宽度 double scale = 0;// 定义小图片和原图片比例 if (maxPixel != 0) { if (imageWidth > imageHeight) { changeWidth = maxPixel; scale = (double) changeWidth / (double) imageWidth; changeHeight = (int) (imageHeight * scale); } else { changeHeight = maxPixel; scale = (double) changeHeight / (double) imageHeight; changeWidth = (int) (imageWidth * scale); } } // 生成转换比例 transform.setToScale(scale, scale); // 生成转换操作对象 AffineTransformOp transOp = new AffineTransformOp(transform, null); //生成压缩图片缓冲对象 BufferedImage basll = new BufferedImage(changeWidth, changeHeight, BufferedImage.TYPE_3BYTE_BGR); //生成缩小图片 transOp.filter(image, basll); try { //输出缩小图片 ImageIO.write(basll, "jpeg",tarImage); } catch (IOException e) { e.printStackTrace(); } } }