Java将图片压缩为原来的一半
思路:
1.获取源图片的尺寸
2.设置目标图片的尺寸
3.打开源图片
4.基于源图片生成目标图片
ps: 在linux上无法使用JPEGImageEncoder ,因此需要修改代码,使用ImageIO代替JPEGImageEncoder
/*JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
sLogger.info("create encoder done");
encoder.encode(outImage);
sLogger.info("encoder done");*/
ImageIO.write(outImage, "jpg", out);
out.flush();
out.close();
/**
* 压缩为input的1/2
* @param filesrc
* @param outsrc
*/
public static void composePic(String inFileName, String outFileName) {
try {
File inFile = new File(inFileName);
Image inImage = javax.imageio.ImageIO.read(inFile);
//get the input image's width and height
int input_width = inImage.getWidth(null);
int input_height = inImage.getHeight(null);
System.out.println("input_width = " + input_width);
System.out.println("input_height = " + input_height);
//set the output image's width and height
int out_width = input_width/2;
int out_height = input_height/2;
BufferedImage outImage = new BufferedImage(out_width, out_height,
BufferedImage.TYPE_INT_RGB);//an image with 8-bit RGB color
Graphics2D g2d = outImage.createGraphics();
g2d.drawImage(inImage, 0, 0, out_width, out_height, null);
g2d.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_ATOP, 1.0f)); // 透明度设置开始
g2d.setComposite(AlphaComposite
.getInstance(AlphaComposite.SRC_OVER)); // 透明度设置 结束
FileOutputStream out = new FileOutputStream(outFileName);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(outImage);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}