最近工作需要对服务器上面的文件进行压缩,并且把原来一些缩略图进行压缩。贴出代码片断供大家交流。
搜略图实现规定大小画布上缩小图片,方便列表显示。
图片压缩提供了2种方法。1、可以自定义压缩比。2、采用ImageIO进行默认压缩(更安全一些,不会出现内存溢出)。
private
void
doThumbCompress(File file)
{
BufferedImage bis
=
null
;
BufferedImage bid
=
null
;
try
{
int
nw
=
113
;
//
定义宽为113
int
nh
=
84
;
//
定义高为84
bis
=
ImageIO.read(file);
int
c_w
=
bis.getWidth();
int
c_h
=
bis.getHeight();
if
(c_w
<
114
&&
file.length()
<
MIN_LENGTH)
{
bis
=
null
;
return
;
}
if
(c_w
>
WIDTH)
{
nw
=
WIDTH;
nh
=
c_h
*
(WIDTH)
/
c_w;
c_h
=
nh;
c_w
=
nw;
}
if
(c_h
>
HEIGHT)
{
nh
=
HEIGHT;
nw
=
c_w
*
(HEIGHT)
/
c_h;
}
bid
=
new
BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g
=
bid.getGraphics();
g.setColor(Color.white);
g.fillRect(
0
,
0
, WIDTH, HEIGHT);
g.drawImage(bis,(WIDTH
-
nw)
/
2
,
0
,nw,nh,
null
);
long
oldFileSize
=
file.length();
if
(isOverlay)
{
ImageIO.write(bid,
"
jpeg
"
, file);
}
else
{
ImageIO.write(ImageIO.read(file),
"
jpeg
"
,
new
File(outPath
+
File.separator
+
file.getName()));
}
long
newFileSize
=
file.length();
log(
"
ok:
"
+
file
+
"
\t
"
+
oldFileSize
+
"
\t
"
+
newFileSize);
}
catch
(Exception e)
{
log(file
+
"
error:
"
+
e.getMessage());
}
bis
=
null
;
bid
=
null
;
}
压缩图片代码:
/** *//**
* 可以自定义压缩比例
* @param file
*/
private void doCompressQuality(File file) {
BufferedImage src = null;
FileOutputStream out = null;
JPEGImageEncoder encoder = null;
JPEGEncodeParam param = null;
try{
src= ImageIO.read(file);//or png.
if(isOverlay){
out= new FileOutputStream(file);
}else{
out= new FileOutputStream(outPath+File.separator+file.getName());
}
encoder= JPEGCodec.createJPEGEncoder(out);
param= encoder.getDefaultJPEGEncodeParam(src);
param.setQuality(imageQuality, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(src);//近JPEG编码
out.close();
//ImageIO.write(src, "jpeg", new File(outPath+File.separator+file.getName()));
log("over:"+file.getPath());
} catch (IOException e){
log("compress error:"+file.getPath()+";error:"+e.getMessage());
}
out = null;
encoder = null;
param = null;
src = null;
}
/** *//**
* 压缩图片,默认压缩比例75%
* @param file
*/
private void doCompress(File file){
File descFile = null;
boolean writeOk=false;
long fileSize=file.length();
try{
if(isOverlay){
descFile = file;
writeOk = ImageIO.write(ImageIO.read(file), "jpeg", descFile);
}else{
descFile = new File(outPath+File.separator+file.getName());
writeOk = ImageIO.write(ImageIO.read(file), "jpeg", descFile);
}
if(writeOk){
log("ok:"+file.getPath()+"\t"+fileSize+"\t"+descFile.length());
}else{
log("fail:"+file.getPath()+"\t"+fileSize+"\t"+descFile.length());
}
} catch (Exception e){
log("compress error:"+file.getPath()+";descFile="+descFile+";error:"+e.getMessage());
}
descFile=null;
}