public static void main(String[] args) {
try {
//图片所在路径
BufferedImage templateImage = ImageIO.read(new File("C:\\Users\\晏丁丁\\Pictures\\图片1.png"))
//原始图片的长度和宽度
int height = templateImage.getHeight()
int width = templateImage.getWidth()
//通过比例压缩
float scale = 0.5f
//通过固定长度压缩
/*int doWithHeight = 100
int dowithWidth = 300*/
//压缩之后的长度和宽度
int doWithHeight = (int) (scale * height)
int dowithWidth = (int) (scale * width)
BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB)
finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null)
//图片输出路径,以及图片名
FileOutputStream fileOutputStream = new FileOutputStream("D:/image/tupian.jpg")
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream)
encoder.encode(finalImage)
fileOutputStream.close()
} catch (IOException e) {
e.printStackTrace()
}
}
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
30
31
32
33
34
35
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
30
31
32
33
34
35
文章知
缩小即可。javathumbnails压缩图片占用内存过大的解决办法:1、打开压缩图网站,点击选择图片压缩按钮。
2、图片上传前网站默认的压缩等级是70,图片上传后会自动按照当前设置的压缩等级进行压缩,如果压缩后的大小不合要求,可再次设置图片的宽高尺寸、压缩等级等参数,宽高留空时默认按照原图尺寸进行压缩,压缩等级越小则压缩后的图片体积越小,最后点击开始压缩按钮重新压缩。
3、图片压缩后,我们就能明显的看到图片压缩后的体积缩小了很多,点击“保存图片”即可。