actuallymicah
actuallymicah

Reputation: 709

Flutter: Some images are displayed sideways(rotated 90 degrees)

On iOS some photos are displayed sideways (i.e rotated 90 degrees). This seems to affect some photos randomly but consistently(i.e photos that are displayed sideways are always displayed sideways) and happens more often with Live Photos. I use image_picker (https://pub.dev/packages/image_picker) to select the images. The problem persists irrespective of the widget used to display the photo.

Screenshot of issue

Upvotes: 5

Views: 5468

Answers (1)

actuallymicah
actuallymicah

Reputation: 709

Using this article as the starting point, I was able to fix it by analyzing different images where rotation happens to tease out a pattern. This may be very specific to my case but it works for me at this point.

Future<void> applyRotationFix(String originalPath) async {
  try {
    Map<String, IfdTag> data = await readExifFromFile(File(originalPath));
    print(data);

    int length = int.parse(data['EXIF ExifImageLength'].toString());
    int width = int.parse(data['EXIF ExifImageWidth'].toString());
    String orientation = data['Image Orientation'].toString();

    if (length != null && width != null && orientation != null) {
      if (length > width) {
        if (orientation.contains('Rotated 90 CW')) {
          img.Image original =
              img.decodeImage(File(originalPath).readAsBytesSync());
          img.Image fixed = img.copyRotate(original, -90);
          File(originalPath).writeAsBytesSync(img.encodeJpg(fixed));
        } else if (orientation.contains('Rotated 180 CW')) {
          img.Image original =
              img.decodeImage(File(originalPath).readAsBytesSync());
          img.Image fixed = img.copyRotate(original, -180);
          File(originalPath).writeAsBytesSync(img.encodeJpg(fixed));
        } else if (orientation.contains('Rotated 270 CW')) {
          img.Image original =
              img.decodeImage(File(originalPath).readAsBytesSync());
          img.Image fixed = img.copyRotate(original, -270);
          File(originalPath).writeAsBytesSync(img.encodeJpg(fixed));
        }
      }
    }
  } catch (e) {
    print(e.toString());
  }
}

Upvotes: 5

Related Questions