本文實(shí)例為大家分享了java實(shí)現(xiàn)圖片壓縮的相關(guān)代碼,供大家參考,具體內(nèi)容如下
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import javax.imageio.ImageIO; public class ImageProcess { /** * 圖片 */ private Image img; /** * 寬度 */ private int width; /** * 高度 */ private int height; /** * 文件格式 */ private String imageFormat; /** * 構(gòu)造函數(shù) * @throws Exception */ public ImageProcess(InputStream in,String fileName) throws Exception{ //構(gòu)造Image對象 img = ImageIO.read(in); //得到源圖寬 width = img.getWidth( null ); //得到源圖長 height = img.getHeight( null ); //文件格式 imageFormat = fileName.substring(fileName.lastIndexOf( "." )+ 1 ); } /** * 按照寬度還是高度進(jìn)行壓縮 * @param w int 最大寬度 * @param h int 最大高度 */ public byte [] resizeFix( int w, int h) throws IOException { if (width / height > w / h) { return resizeByWidth(w); } else { return resizeByHeight(h); } } /** * 以寬度為基準(zhǔn),等比例放縮圖片 * @param w int 新寬度 */ public byte [] resizeByWidth( int w) throws IOException { int h = ( int ) (height * w / width); return resize(w, h); } /** * 以高度為基準(zhǔn),等比例縮放圖片 * @param h int 新高度 */ public byte [] resizeByHeight( int h) throws IOException { int w = ( int ) (width * h / height); return resize(w, h); } /** * 強(qiáng)制壓縮/放大圖片到固定的大小 * @param w int 新寬度 * @param h int 新高度 */ public byte [] resize( int w, int h) throws IOException { // SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 優(yōu)先級比速度高 生成的圖片質(zhì)量比較好 但速度慢 BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0 , 0 , w, h, null ); // 繪制縮小后的圖 ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, imageFormat, baos); return baos.toByteArray(); } } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,輕松實(shí)現(xiàn)圖片壓縮操作。