Home > Software engineering >  Java Image BufferedImage loosing aspect ratio of upright image
Java Image BufferedImage loosing aspect ratio of upright image

Time:12-03

I am storing an Image in the filesystem like:

FileImageOutputStream fos = new FileImageOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
      fos.write(buffer, 0, len);
}
fos.close();

And all images are stored correctly in the filesystem. (Also with correct aspect ratio with width and height!)

However, later, I am loading my image like:

File imgFile ...
FileImageInputStream stream = new FileImageInputStream(imgFile);
BufferedImage srcImage = ImageIO.read(stream);

And I want to get the width and height for my images like:

int actualHeight = srcImage.getHeight();
int actualWidth = srcImage.getWidth();

This works totally fine for images in landscape format. However, for images in upfront format, the width and height is always swapped, so that the width is the height of the orginial image. So, e.g. I have an image that is 200x500 (width x height) and the two integers above are actualHeight = 200 and actualWidth = 500.

Am I missing something?

SOLUTION:

The maybe easiest way to achieve this, is just to use thumbnailator (https://github.com/coobird/thumbnailator):

        BufferedImage srcImage = Thumbnails.of(new FileInputStream(imgFile)).scale(1).asBufferedImage();

reads the image in correct orientation

CodePudding user response:

It is likely that the image is being read in the incorrect orientation. When reading the image, you can try specifying the orientation of the image to ensure that it is read correctly. You can do this by using the ImageReader.setInput method and specifying the ImageReadParam.setSourceRegion parameter.

Here is an example:

// create a reader for the image file
ImageReader reader = ImageIO.getImageReadersByFormatName("jpg").next();
reader.setInput(new FileImageInputStream(imgFile));

// specify the region of the image to read
ImageReadParam param = reader.getDefaultReadParam();
param.setSourceRegion(new Rectangle(0, 0, actualWidth, actualHeight));

// read the image using the specified region
BufferedImage srcImage = reader.read(0, param);

// get the width and height of the image
int imageWidth = srcImage.getWidth();
int imageHeight = srcImage.getHeight();

// close the reader
reader.dispose();

This should ensure that the image is read in the correct orientation and the width and height values are correct.

  • Related