Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHImageManager returning images with incorrect orientation on device

Tags:

ios

xcode6

ios8

I provide the user the ability to pick photos from their camera roll to upload to the server.

The orientation appears correct in the camera roll.

When I use the simulator (iphone5, iphone6 etc..) everything works as expected and the orientation of the photo is correct when uploaded to the server.

When I attach a device and select a photo the image is always oriented 90 CCW. If I logout image.imageOrientation right before saving the result I can see its '3' meaning UIImageOrientationRight.

Does anyone have any insight why on the device its 90 CCW and on simulator is correct?

Here is my code:

(event.eventAttachments is an array of PHAssets)

__block NSMutableArray *images = [[NSMutableArray alloc] init];

PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.networkAccessAllowed = YES;
options.synchronous = YES;

for(id asset in event.eventAttachments) {
  CGFloat scale = [UIScreen mainScreen].scale;
  CGSize targetSize = CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds) * scale, CGRectGetHeight([UIScreen mainScreen].bounds) * scale);
  [[PHImageManager defaultManager] requestImageForAsset:asset
    targetSize:targetSize
    contentMode:PHImageContentModeAspectFit
    options:options
    resultHandler:^(UIImage *result, NSDictionary *info) {
    if (result) {
      NSMutableDictionary *imageDict = [[NSMutableDictionary alloc] init];
      [imageDict setObject:result forKey:@"image"];
      [imageDict setObject:[NSString stringWithFormat:@"image.jpg"] forKey:@"name"];
      [images addObject: imageDict];
    }
  }];

}

I NSLog the image.UIImageOrientation and I see 3.

EDIT: wanted to add that if I use my device, and I go onto google images and download a random image and then select that image the orientation is correct.

So the orientation is only wrong for photos that have been taken with a device. Because the simulator I am using the 'stock' images that come with the simulator (since I can't take photos with my simulator).

like image 706
nwkeeley Avatar asked Oct 20 '22 02:10

nwkeeley


1 Answers

I solved my problem by running the image through this first:

- (UIImage *)normalizedImage: (UIImage *)image {
    if (image.imageOrientation == UIImageOrientationUp) return image;
    UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);
    [image drawInRect:(CGRect){0, 0, image.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return normalizedImage;
}

Thanks to an0's answer here

like image 150
nwkeeley Avatar answered Nov 15 '22 05:11

nwkeeley