How to detect if an image is vertical or horizontal

Viewed 1001

I am making an App in Flutter in which I use image_picker and I would like to know how to know the orientation of an image, if an image is vertical or horizontal.

Is there any way to do it?

3 Answers

Once you get the file from picker, convert to Image and get the width & height, calculate the ratio then you get the orientation:

image = Image.memory(await pickedFile.readAsBytes())

decodeImageFromList() provides us the height and width of the image, based on the size we can decide whether the given image is vertical or horizontal.

    import 'dart:io';

    final picker = ImagePicker();
    final pickedFile = await picker.getImage(source: ImageSource.camera);

    File image = new File(pickedFile.path); 
    var decodedImage = await decodeImageFromList(image.readAsBytesSync());
    bool isHorizontalImage = decodedImage.width > decodedImage.height;

The correct way to read the orientation of an image file is to read its metadata. Whenever any image file is created then it also creates the Exif file (or metadata file). This EXIF file contains all the properties of an image like orientation, width, height, etc.

using the readAsBytes function will give you EXIF metadata.

The orientation of an image depends on the way you hold your camera. If you have captured by holding the camera upside down then your image will have vertical orientation but the image content will be upside down.

There is a total of 8 orientations that an image supports. you can read more about it here https://sirv.com/help/articles/rotate-photos-to-be-upright/

But if you are looking to find the orientation only then you can find it using the EXIF file using the readAsBytes function and access the orientation property.

Related