3

I am just starting to learn iPhone app development. I am trying to retrieve photos from my photo album using ALAsset class and upload the photos to my server. However, the photos that were taken in the Portrait mode are rotated 90 degrees to the left while the landscape photos are properly uploaded. What am I doing wrong? In the NSLog, I do see the orientation to be 3, but still the photo is rotated to 90 degrees to the left. Any help will be greatly appreciated.

Here's the snippet of my code:

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];

   imagePath = [[documentsDirectory stringByAppendingPathComponent:@"latest_photo.jpg"] copy];
   NSLog(@"imagePath = %@", imagePath);

   ALAssetRepresentation *rep = [myasset defaultRepresentation];
   ALAssetOrientation orientation = [rep orientation];
   NSLog(@"Orientation = %d", orientation);

   CGImageRef iref = [rep fullResolutionImage];

   if (iref) {
      UIImage *largeimage = [UIImage imageWithCGImage:iref scale:1.0 orientation:orientation];
      NSData *webData = UIImageJPEGRepresentation(largeimage,0.5);

      [webData writeToFile:imagePath atomically:YES];

      // Upload the image
Derek Beattie
  • 9,429
  • 4
  • 30
  • 44
Balaji Krishnan
  • 101
  • 3
  • 5

2 Answers2

8

For the asset orientation part of your code, instead of

ALAssetRepresentation *rep = [myasset defaultRepresentation];
ALAssetOrientation orientation = [rep orientation];

Try

ALAssetOrientation orientation = [[asset valueForProperty:@"ALAssetPropertyOrientation"] intValue];
zoul
  • 102,279
  • 44
  • 260
  • 354
adriaan
  • 1,574
  • 14
  • 33
0

You can redraw the image into an image context. Then get the image data from the context, and depending on your needs, send the data or store the file to send later.

UIGraphicsBeginImageContext(largeImage.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextRotateCTM(context, M_PI / 2); // Or negative M_PI depending on the image's orientation
largeImage.imageOrientation = UIImageOrientationLeft;
[largeImage drawAtPoint:CGPointZero];
NSData *rotatedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

You might need the 'right' image orientation, depending on which way your portrait photos are rotated, but its just a matter of making one test.

Javier C
  • 726
  • 5
  • 15