Java图片大小转换

最近做一系统,要求输出图片的大小不大于500K,在网上找了一下,资料很多,整理了一下代码,可以实现图片固定比例输出。代码如下:

Java
/**
 * Jpg图片文件转换
 * @param inFile
 * @param outFile
 * @return
 */
private static boolean compressPic(File inFile, File outFile) {
    try {
        int outWidth = OUTPUT_WIDTH;
        int outHeight = OUTPUT_HEIGHT;
        Image img = ImageIO.read(inFile);

        if (img.getWidth(null) == -1) {
            return false;
        } else {
            int newWidth;
            int newHeight;

            double rate1 = ((double) img.getWidth(null)) / (double) outWidth + 0.1;
            double rate2 = ((double) img.getHeight(null)) / (double) outHeight + 0.1;

            double rate = rate1 > rate2 ? rate1 : rate2;
            newWidth = (int) (((double) img.getWidth(null)) / rate);
            newHeight = (int) (((double) img.getHeight(null)) / rate);

            BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight,
                    BufferedImage.TYPE_INT_RGB);

            tag.getGraphics().drawImage(
                    img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
            FileOutputStream out = new FileOutputStream(outFile);

            ImageIO.write(tag, "jpeg", out);
            out.close();
        }
    } catch (IOException ex) {
        return false;
    }

    return true;
}

参考地址:http://zeng168cn.iteye.com/blog/741214

转载请注明:宇托的狗窝 » Java图片大小转换

发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址