缩放图片的代码
public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
// targetW,targetH分别表示目标长和宽
int type = source.getType();
BufferedImage target = null;
double sx = (double) targetW / source.getWidth();
double sy = (double) targetH / source.getHeight();
//这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
//则将下面的if else语句注释即可
if(sx>sy)
{
sx = sy;
targetW = (int)(sx * source.getWidth());
}else{
sy = sx;
targetH = (int)(sy * source.getHeight());
}
if (type == BufferedImage.TYPE_CUSTOM) { //handmade
ColorModel cm = source.getColorModel();
WritableRaster raster = cm.createCompatibleWritableRaster(targetW, targetH);
boolean alphaPremultiplied = cm.isAlphaPremultiplied();
target = new BufferedImage(cm, raster, alphaPremultiplied, null);
} else
target = new BufferedImage(targetW, targetH, type);
Graphics2D g = target.createGraphics();
//smoother than exlax:
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
g.dispose();
return target;
}
将InputStream保存为jpg文件
public static void saveImageAsJpg (InputStream in, File saveFile,int width,int hight)
throws Exception {
BufferedImage srcImage;
srcImage = ImageIO.read(in);
if(width > 0 || hight > 0)
{
srcImage = resize(srcImage, width, hight);
}
ImageIO.write(srcImage, "JPEG", saveFile);
in.close();
}
将InputStream保存为gif文件
private static void saveImageAsGif(InputStream in, File fileToSave,int width, int hight)
throws Exception {
BufferedImage srcImage;
srcImage = ImageIO.read(in);
if(width>0 && hight >0)
{
srcImage = resize(srcImage, width, hight);
}
FileOutputStream out = new FileOutputStream(fileToSave);
GifEncoder encoder = new GifEncoder(srcImage, out);
encoder.encode();
in.close();
}