image.ImageCompression.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package
image;
import
com.sun.image.codec.jpeg.JPEGCodec;
import
com.sun.image.codec.jpeg.JPEGImageEncoder;
import
javax.imageio.ImageIO;
import
java.awt.image.BufferedImage;
import
java.io.*;
public
class
ImageCompression {
public
static
void
compressImage(File originalImage,
int
width,
int
height,File destFile)
throws
Exception{
// 压缩图片
BufferedImage originalBufferedImage = ImageIO.read(originalImage);
// int originalWidth = originalBufferedImage.getWidth(); // 原始宽度
// int originalHeight = originalBufferedImage.getHeight();// 原始高度
// int resizeWidth = originalWidth/4; // 压缩后 宽度
// int resizeHeight = originalHeight/4; // 压缩后 高度
BufferedImage resizedBufferedImage =
new
BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
resizedBufferedImage.getGraphics().drawImage(originalBufferedImage,
0
,
0
,width,height,
null
);
FileOutputStream fos =
new
FileOutputStream(destFile);
// 输出到文件流
// 可以正常实现bmp、png、gif转jpg
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
encoder.encode(resizedBufferedImage);
// JPEG编码
fos.close();
}
public
static
void
main(String[] args)
throws
Exception{
compressImage(
new
File(
"dest.jpg"
),
200
,
200
,
new
File(
"resized_dest.jpg"
));
}
}
|
本文转自 antlove 51CTO博客,原文链接:http://blog.51cto.com/antlove/1727591