Java图片大小转换

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

/**
 * 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

发表评论

电子邮件地址不会被公开。 必填项已用*标注