用awt缩放图片
众所周知缩放图片时用imagemagick的效果好。不过用起来不是很方便。在linux下倒还方便。在win下用就没那么方便了。
对效果要求不高可以用awt来缩放就可以了。下面就简要介绍一下其方法:
public final class ThumbUtils { private ThumbUtils() { }
/*** @param in * @param out * @param formatName
* @param size * @throws IOException */
public static void encodeThumb(InputStream in, OutputStream out, PictureSize limitSize, String formatName)
throws IOException
{ BufferedImage image = ImageIO.read(in);
encodeThumb(image, out, limitSize, formatName);
}
public static void encodeThumb(BufferedImage image, OutputStream out, PictureSize limitSize, String formatName)
throws IOException {
PictureSize originalSize = new PictureSize(image.getWidth(null), image.getHeight(null));
PictureSize thumbSize = getThumbSize(limitSize, originalSize);
int width = thumbSize.getWidth(), height = thumbSize.getHeight();
ColorModel dstCM = image.getColorModel();
BufferedImage dst = new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster(width, height),
dstCM.isAlphaPremultiplied(), null);
Image scaleImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
Graphics2D g = dst.createGraphics();
g.drawImage(scaleImage, 0, 0, width, height, null);
g.dispose();
ImageIO.write(dst, formatName, out); }
/** * @param limitSize * @param originalSize * @return */
public static PictureSize getThumbSize(PictureSize limitSize, PictureSize originalSize)
{
int maxWidth = limitSize.getWidth();
int maxHeight = limitSize.getHeight();
if (maxWidth == 0 && maxHeight == 0) {
maxWidth = maxHeight = DEFAULT_THUMB_SIZE;
}
int originalWidth = originalSize.getWidth();
int originalHeight = originalSize.getHeight();
int width = DEFAULT_THUMB_SIZE, height = DEFAULT_THUMB_SIZE;
float rate = 0;
if (maxWidth > 0 && maxHeight > 0)
{
rate = Math.min(maxWidth * 1f / originalWidth, maxHeight * 1f / originalHeight);
} else if (maxWidth > 0)
{
rate = maxWidth * 1f / originalWidth;
} else if (maxHeight > 0)
{
rate = maxHeight * 1f / originalHeight;
}
else {
// no happen.
}
width = (int) (originalWidth * rate);
height = (int) (originalHeight * rate);
return new PictureSize(width, height);
}
public static final int DEFAULT_THUMB_SIZE = 96; }