上传图片并生成缩略图

最近公司说要在portal中添加一个上传图片并生成缩略图的方法,试了很久,终于搞定了;写下点心得吧,使大家少走弯路;
首先做之前,google了一下,发现很多生产缩略图的方法:
[code]
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;
}
[/code]
但是使用后发现,对于底色是透明的图片,生成的缩略图是别的颜色的,于是找原因,发现jpeg是最大的祸首;
现在修改代码:
[code]
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;
}
[/code]
其中使用了GifEncoder这也类,对应的jar包就是gif89.jar,这是个开源的包,做了修改,去掉了恶心的公司logo,现在生成的缩略图没有问题了,连gif的动画也能缩略,强啊
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值