vamsidhar muthireddy vamsidhar muthireddy - 1 year ago 85
Java Question

Java:getHeight() on BufferedImage is returning image width and getWidth() is returning image height

I am compressing an image doing Jpeg compression in Java and then resizing them before storing. I am keeping the storage height as

and calculating the
based on aspect ratio, so to keep the original
ratio same.

This is the code I am using

String inputImagePath = "1.JPG";
String outputImagePath = "Test Compression\\" + "1.JPG";

File imageFile = new File(inputImagePath);
File compressedImageFile = new File(outputImagePath);

int height = 640;

System.out.print("Conversion Start!\n");

if (imageFile != null)

InputStream is = new FileInputStream(imageFile);
OutputStream os = new FileOutputStream(compressedImageFile);

float quality = 0.2 f;

BufferedImage image =;

double aspectRatio = (double) image.getWidth() / image.getHeight();

width = (int)(height * aspectRatio);
System.out.println("Original height = " + image.getHeight() + " Original width = " + image.getWidth());
System.out.println(" aspect ratio = " + aspectRatio);
System.out.println("height = " + height + " width = " + width + " aspect ratio = " + aspectRatio);

BufferedImage resizedImage = new BufferedImage(width, height, image.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(image, 0, 0, width, height, null);

Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");

if (!writers.hasNext())
throw new IllegalStateException("No writers found");

ImageWriter writer = (ImageWriter);
ImageOutputStream ios = ImageIO.createImageOutputStream(os);

ImageWriteParam param = writer.getDefaultWriteParam();

writer.write(null, new IIOImage(resizedImage, null, null), param);

System.out.print("Conversion compete!");

Here is the image metadata

Here width = 1920, height = 2560

Here is the printed content:

Original height = 1920 Original width = 2560
aspect ratio = 1.3333333333333333

height = 480 width = 640
aspect ratio = 1.3333333333333333

I applied the code to other images which actually had
width > height
and I had no rotation issues. This rotaion issue is only occuring for the images with
height > width
As far as I know there is nothing wrong in my code, I must be missing something related to getHeight() and getWidth() functions. Please help me out

Answer Source

There can be rotation metadata in the jpeg images which Java doesn't recognize by default.

It looks like: Orientation : rotate 90 in the jpeg properties.

You need a 3rd party library to handle it, see How to rotate JPEG images based on the orientation metadata?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download