图像在Java中调整大小以减小图像大小

我有一个说尺寸为800×800的图像,尺寸为170 kb.我想调整此图像的大小,说600×600.调整大小后,我希望减少图像大小.我怎样才能做到这一点?
最佳答案
您不需要一个完整的图像处理库来简单地调整图像大小.

建议的方法是使用渐进式双线性缩放,就像这样(可以在代码中使用此方法):

public BufferedImage scale(BufferedImage img, int targetWidth, int targetHeight) {

    int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
    BufferedImage ret = img;
    BufferedImage scratchImage = null;
    Graphics2D g2 = null;

    int w = img.getWidth();
    int h = img.getHeight();

    int prevW = w;
    int prevH = h;

    do {
        if (w > targetWidth) {
            w /= 2;
            w = (w < targetWidth) ? targetWidth : w;
        }

        if (h > targetHeight) {
            h /= 2;
            h = (h < targetHeight) ? targetHeight : h;
        }

        if (scratchImage == null) {
            scratchImage = new BufferedImage(w, h, type);
            g2 = scratchImage.createGraphics();
        }

        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null);

        prevW = w;
        prevH = h;
        ret = scratchImage;
    } while (w != targetWidth || h != targetHeight);

    if (g2 != null) {
        g2.dispose();
    }

    if (targetWidth != ret.getWidth() || targetHeight != ret.getHeight()) {
        scratchImage = new BufferedImage(targetWidth, targetHeight, type);
        g2 = scratchImage.createGraphics();
        g2.drawImage(ret, 0, 0, null);
        g2.dispose();
        ret = scratchImage;
    }

    return ret;

}

Filthy Rich Clients修改并清除原始代码.

根据您的评论,您可以降低质量并编码JPEG字节,如下所示:

image是BufferedImage.

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName("jpeg").next();

ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(0.2f); // Change this, float between 0.0 and 1.0

writer.setOutput(ImageIO.createImageOutputStream(os));
writer.write(null, new IIOImage(image, null, null), param);
writer.dispose();

现在,因为os是ByteArrayOutputStream,所以你可以对其进行Base64编码.

String base64 = Base64.encode(os.toByteArray());

转载注明原文:图像在Java中调整大小以减小图像大小 - 代码日志