我想知道是否可以在不创建另一个图像的新实例的情况下调整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,BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp,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,targetWidth,null);
g2d.dispose();
return bi;
}
感谢您的任何答复!