看了一些网上的代码,总觉得,是在计算机出长和宽,起始坐标后 裁减了原图片,到底能不能实现压缩,比如:原图的大小为 310*330 我现在想把长固定为220然后宽压缩为 220/310*330 的效果?
用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; }
jmagick ( http://www.jmagick.org/index.html ),imagemagick的Java实现。可以用
淘宝网使用GraphicsMagick处理图片,据说比imagemagick更高效,Java API:im4java。
php的GD库毫无压力的做到……imagemagick当然也行了,其java实现就是@gaosboy所说的jmagick拉。