最近公司说要在portal中添加一个上传图片并生成缩略图的方法,试了很久,终于搞定了;写下点心得吧,使大家少走弯路;
首先做之前,google了一下,发现很多生产缩略图的方法:
BufferedImage img = ImageIO.read(file);
int h = img.getHeight();
int w = img.getWidth();
if(h>=96 && w >=96){
int nw = 96;
int nh = (nw * h) / w;
if(nh>96) {
nh = 96;
nw = (nh * w) / h;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage dest = new BufferedImage(nw, nh, BufferedImage.TYPE_INT_RGB);
dest.getGraphics().drawImage(img,0,0,nw, nh,null);
ImageIO.write(dest, "jpeg", out);
imageThumbnail = out.toByteArray();
}
else{
imageThumbnail = imageData;
}
但是使用后发现,对于底色是透明的图片,生成的缩略图是别的颜色的,于是找原因,发现jpeg是最大的祸首;
现在修改代码:
BufferedImage img = ImageIO.read(file);
int h = img.getHeight();
int w = img.getWidth();
if(h>=96 && w >=96){
int nw = 96;
int nh = (nw * h) / w;
if(nh>96) {
nh = 96;
nw = (nh * w) / h;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage dest = new BufferedImage(nw, nh,BufferedImage.TYPE_4BYTE_ABGR);
dest.getGraphics().drawImage(img,0,0,nw, nh,null);
GifEncoder.encode(dest, out);
//ImageIO.write(dest, "gif", out);
imageThumbnail = out.toByteArray();
}
else{
imageThumbnail = imageData;
}
其中使用了GifEncoder这也类,对应的jar包就是gif89.jar,这是个开源的包,做了修改,去掉了恶心的公司logo,现在生成的缩略图没有问题了,连gif的动画也能缩略,强啊