JAVA压缩图片
在我们浏览网页的时候,我们呢时常见到这样的效果,点击小图见大图,这里用到的技术便是图片压缩技术,是两张图片,不过是名字一样,
在java中,同样可以实现图片的压缩处理,在网上好像找不到拿来就能用的,下面的这个可以用,
但是有一些限制,只能压缩一些特定的图片文件,jpg,png,gif(非动画),大家可以研究下代码,
根据代码自己去扩展合适的压缩类型,实际中,这些已经差不多可以运用了,
下面是代码和在junit单元测试实例
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
|
package
com.sport.utils;
import
java.awt.Color;
import
java.awt.Component;
import
java.awt.Graphics;
import
java.awt.Graphics2D;
import
java.awt.Image;
import
java.awt.MediaTracker;
import
java.awt.Toolkit;
import
java.awt.image.BufferedImage;
import
java.awt.image.ConvolveOp;
import
java.awt.image.Kernel;
import
java.io.ByteArrayOutputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.FileOutputStream;
import
java.io.IOException;
import
java.io.OutputStream;
import
javax.imageio.ImageIO;
import
javax.swing.ImageIcon;
import
com.sun.image.codec.jpeg.JPEGCodec;
import
com.sun.image.codec.jpeg.JPEGEncodeParam;
import
com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
* 图像压缩工具
* @author
*
*/
public
class
ImageSizer {
public
static
final
MediaTracker tracker =
new
MediaTracker(
new
Component() {
private
static
final
long
serialVersionUID = 1234162663955668507L;}
);
/**
* @param originalFile 原图像
* @param resizedFile 压缩后的图像
* @param width 图像宽
* @param format 图片格式 jpg, png, gif(非动画)
* @throws IOException
*/
public
static
void
resize(File originalFile, File resizedFile,
int
width, String format)
throws
IOException {
if
(format!=
null
&&
"gif"
.equals(format.toLowerCase())){
resize(originalFile, resizedFile, width,
1
);
return
;
}
FileInputStream fis =
new
FileInputStream(originalFile);
ByteArrayOutputStream byteStream =
new
ByteArrayOutputStream();
int
readLength = -
1
;
int
bufferSize =
1024
;
byte
bytes[] =
new
byte
[bufferSize];
while
((readLength = fis.read(bytes,
0
, bufferSize)) != -
1
) {
byteStream.write(bytes,
0
, readLength);
}
byte
[] in = byteStream.toByteArray();
fis.close();
byteStream.close();
Image inputImage = Toolkit.getDefaultToolkit().createImage( in );
waitForImage( inputImage );
int
imageWidth = inputImage.getWidth(
null
);
if
( imageWidth <
1
)
throw
new
IllegalArgumentException(
"image width "
+ imageWidth +
" is out of range"
);
int
imageHeight = inputImage.getHeight(
null
);
if
( imageHeight <
1
)
throw
new
IllegalArgumentException(
"image height "
+ imageHeight +
" is out of range"
);
// Create output image.
int
height = -
1
;
double
scaleW = (
double
) imageWidth / (
double
) width;
double
scaleY = (
double
) imageHeight / (
double
) height;
if
(scaleW >=
0
&& scaleY >=
0
) {
if
(scaleW > scaleY) {
height = -
1
;
}
else
{
width = -
1
;
}
}
Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);
checkImage( outputImage );
encode(
new
FileOutputStream(resizedFile), outputImage, format);
}
/** Checks the given image for valid width and height. */
private
static
void
checkImage( Image image ) {
waitForImage( image );
int
imageWidth = image.getWidth(
null
);
if
( imageWidth <
1
)
throw
new
IllegalArgumentException(
"image width "
+ imageWidth +
" is out of range"
);
int
imageHeight = image.getHeight(
null
);
if
( imageHeight <
1
)
throw
new
IllegalArgumentException(
"image height "
+ imageHeight +
" is out of range"
);
}
/** Waits for given image to load. Use before querying image height/width/colors. */
private
static
void
waitForImage( Image image ) {
try
{
tracker.addImage( image,
0
);
tracker.waitForID(
0
);
tracker.removeImage(image,
0
);
}
catch
( InterruptedException e ) { e.printStackTrace(); }
}
/** Encodes the given image at the given quality to the output stream. */
private
static
void
encode( OutputStream outputStream, Image outputImage, String format )
throws
java.io.IOException {
int
outputWidth = outputImage.getWidth(
null
);
if
( outputWidth <
1
)
throw
new
IllegalArgumentException(
"output image width "
+ outputWidth +
" is out of range"
);
int
outputHeight = outputImage.getHeight(
null
);
if
( outputHeight <
1
)
throw
new
IllegalArgumentException(
"output image height "
+ outputHeight +
" is out of range"
);
// Get a buffered image from the image.
BufferedImage bi =
new
BufferedImage( outputWidth, outputHeight,
BufferedImage.TYPE_INT_RGB );
Graphics2D biContext = bi.createGraphics();
biContext.drawImage( outputImage,
0
,
0
,
null
);
ImageIO.write(bi, format, outputStream);
System.out.println(
"----the end ------"
);
outputStream.flush();
outputStream.close();
}
/**
* 缩放gif图片
* @param originalFile 原图片
* @param resizedFile 缩放后的图片
* @param newWidth 宽度
* @param quality 缩放比例 (等比例)
* @throws IOException
*/
private
static
void
resize(File originalFile, File resizedFile,
int
newWidth,
float
quality)
throws
IOException {
if
(quality <
0
|| quality >
1
) {
throw
new
IllegalArgumentException(
"Quality has to be between 0 and 1"
);
}
ImageIcon ii =
new
ImageIcon(originalFile.getCanonicalPath());
Image i = ii.getImage();
Image resizedImage =
null
;
int
iWidth = i.getWidth(
null
);
int
iHeight = i.getHeight(
null
);
if
(iWidth > iHeight) {
resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);
}
else
{
resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);
}
// This code ensures that all the pixels in the image are loaded.
Image temp =
new
ImageIcon(resizedImage).getImage();
// Create the buffered image.
BufferedImage bufferedImage =
new
BufferedImage(temp.getWidth(
null
), temp.getHeight(
null
),
BufferedImage.TYPE_INT_RGB);
// Copy image to buffered image.
Graphics g = bufferedImage.createGraphics();
// Clear background and paint the image.
g.setColor(Color.white);
g.fillRect(
0
,
0
, temp.getWidth(
null
), temp.getHeight(
null
));
g.drawImage(temp,
0
,
0
,
null
);
g.dispose();
// Soften.
float
softenFactor =
0
.05f;
float
[] softenArray = {
0
, softenFactor,
0
, softenFactor,
1
-(softenFactor*
4
), softenFactor,
0
, softenFactor,
0
};
Kernel kernel =
new
Kernel(
3
,
3
, softenArray);
ConvolveOp cOp =
new
ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP,
null
);
bufferedImage = cOp.filter(bufferedImage,
null
);
// Write the jpeg to a file.
FileOutputStream out =
new
FileOutputStream(resizedFile);
// Encodes image as a JPEG data stream
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
param.setQuality(quality,
true
);
encoder.setJPEGEncodeParam(param);
encoder.encode(bufferedImage);
}
}
|
单元测试,看如何使用
1
2
3
4
5
6
7
8
9
10
|
@Test
public
void
imagetest(){
try
{
ImageSizer.resize(
new
File(
"f:\\image\\363.jpg"
),
new
File(
"f:\\image\\testabc.jpg"
),
100
,
"jpg"
);
}
catch
(IOException e) {
e.printStackTrace();
}
}
|