如何获取调整大小的BufferedImage

时间:2015-01-20 12:34:32

标签: java image awt bufferedimage javax.imageio

假设我有2张TIF张图片,我将其中一张图片读入BufferedImage个实例:

ImageReader reader = ImageIO.getImageReadersByFormatName("tif").next();
reader.setInput(inputStream, false);   // inputStream is the first image.
BufferedImage bufferedImage = reader.read(0);

现在我想创建一个新的BufferedImage 而不读取其他图像。它应该与前一个相同,但尺寸不同。 <{1}}图像的imageType似乎为0,但以下情况不起作用。

TIF

有没有办法克隆现有的BufferedImage largeBufferedImage = new BufferedImage(newWidth, newHeight, 0); 而只改变它的大小?

BTW我希望能够为任何图像格式做到这一点。如果可能的话,我不想处理像BufferedImage这样的细节。

3 个答案:

答案 0 :(得分:1)

BufferedImage deepCopy(BufferedImage bi)/*method to clone BufferedImage*/ {
   ColorModel cm = bi.getColorModel();
   boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
   WritableRaster raster = bi.copyData(null);
   return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
BufferedImage newImg = deepCopy(oldImg);//clone it
Graphics2D g = newImg.createGraphics();
g.drawImage(newImg, 0, 0, width, height, null);//newImg will be resized

答案 1 :(得分:0)

当您使用paint方法绘制时,可以添加更多参数来拉伸和缩放图像,请参阅此link上的g.drawImage

答案 2 :(得分:0)

经过一些反复试验,我找到了解决问题的有效方法。

private BufferedImage copyAndResize(BufferedImage source, int width, int height)
{
    ColorModel cm = source.getColorModel();
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    WritableRaster raster = source.copyData(null);
    SampleModel sm = raster.getSampleModel().createCompatibleSampleModel(width, height);
    WritableRaster newRaster = WritableRaster.createWritableRaster(sm, null);
    BufferedImage newBi = new BufferedImage(cm, newRaster, isAlphaPremultiplied, null);
    return newBi;
}