2

我想知道是否有一种方法可以在不创建另一个图像的新实例的情况下调整 BufferedImage 的大小。我想知道这一点,因为我认为每次我想为我的应用程序调整 BufferedImage 的大小时创建一个新图像效率低下。这是我看到的一些代码,它解释了我不想要的内容:

public static BufferedImage resize(BufferedImage img, int newW, int newH) { 
    Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
    BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = dimg.createGraphics();
    g2d.drawImage(tmp, 0, 0, null);
    g2d.dispose();

    return dimg;
}
public static BufferedImage scale(BufferedImage src, int w, int h)
{
    BufferedImage img = 
            new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    int x, y;
    int ww = src.getWidth();
    int hh = src.getHeight();
    int[] ys = new int[h];
    for (y = 0; y < h; y++)
        ys[y] = y * hh / h;
    for (x = 0; x < w; x++) {
        int newX = x * ww / w;
        for (y = 0; y < h; y++) {
            int col = src.getRGB(newX, ys[y]);
            img.setRGB(x, y, col);
        }
    }
    return img;
}
private BufferedImage resize(BufferedImage src, int targetSize) {
    if (targetSize <= 0) {
        return src; //this can't be resized
    }
    int targetWidth = targetSize;
    int targetHeight = targetSize;
    float ratio = ((float) src.getHeight() / (float) src.getWidth());
    if (ratio <= 1) { //square or landscape-oriented image
        targetHeight = (int) Math.ceil((float) targetWidth * ratio);
    } else { //portrait image
        targetWidth = Math.round((float) targetHeight / ratio);
    }
    BufferedImage bi = new BufferedImage(targetWidth, targetHeight, src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); //produces a balanced resizing (fast and decent quality)
    g2d.drawImage(src, 0, 0, targetWidth, targetHeight, null);
    g2d.dispose();
    return bi;
}

感谢您的任何回复!

4

0 回答 0