Utku Ufuk
Utku Ufuk

Reputation: 350

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.

Upvotes: 0

Views: 124

Answers (3)

Utku Ufuk
Utku Ufuk

Reputation: 350

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

Upvotes: 0

Jeremy
Jeremy

Reputation: 786

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

Upvotes: 1

Malik Brahimi
Malik Brahimi

Reputation: 16711

When you draw in your paint method, you can add more parameters to stretch and scale image, see g.drawImage at this link.

Upvotes: 0

Related Questions