java 图片压缩100k_java图片压缩

用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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值