简体   繁体   中英

How to obtain a resized BufferedImage

Say I have 2 TIF images and I read one of them into a BufferedImage instance:

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

Now I want to create a new BufferedImage without reading the other image . It should be the same as the previous one, but only different in size. imageType seems to be 0 for TIF images, but the following doesn't work.

BufferedImage largeBufferedImage = new BufferedImage(newWidth, newHeight, 0);

Is there any way to clone the existing BufferedImage and only change its size?

BTW I want to be able to do it for any image format. I don't want to deal with details like imageType if possible.

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

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

After some trial and error, I found a working solution for my problem.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM