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
文章知
Java上传pdf文件,只压缩大小,不改变成.zip/.rar文件可以,压缩只是一种算法,什么语言都可以,比如某种格式的文件中1001010(二进制)代表汉子的"中"字,那么压缩算法就是在编码不冲突的情况下可以改变编码长度,比如压缩之后中字变成1010,这样就节省空间了,这是我随便举的例子,具体的对应算法可以网上查