2

I currently have a JPEG image saved in my app folder with its correct orientation. I need to compress and copy that image to a temporary folder and then send the URL to S3, the way I'm doing it works but the image loses its rotation attribute.

This is what I have:

//I retrieve the image
PHImageManager.defaultManager().requestImageForAsset(p, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info)in
                //Create temp url
                let testFileURL = NSURL(fileURLWithPath: NSTemporaryDirectory().stringByAppendingPathComponent("temp"))

                //Compress the image, I think is here where the orientation is lost
                let data = UIImageJPEGRepresentation(result, 0)

                //Write the image to the tmp folder, or maybe it is here where is lost
                data.writeToURL(testFileURL!, atomically: true)

                //Send URL to upload to S3
                self.uploadImagesToS3(testFileURL!, picName: p.valueForKey("filename") as String, deviceID: deviceID, length: data.length)
            })

Anybody has an idea of what can I do?. The image has the right orientation before the compression and copy, but is rotated after that. The image is taken from the camera.

Thank you!.

Aminix
  • 158
  • 1
  • 11
  • Are these images taken with the camera or are they digital images? – Zane Helton Mar 26 '15 at 01:59
  • It is taken with the camera. – Aminix Mar 26 '15 at 02:06
  • The camera is actually really weird on an iPhone. The rotation is part of the meta data held within the photo and when you compress it, the image loses some of that meta data. That's your reason, but I don't know the solution. Just to verify the issue though I suggest uploading an image that's not taken with a camera and checking what the results are. – Zane Helton Mar 26 '15 at 02:07

1 Answers1

4

This ended up working for me:

I changed this line:

let data = UIImageJPEGRepresentation(result, 0)

For this one:

let data = UIImageJPEGRepresentation(self.correctlyOrientedImage(result), 0)

And added the function:

func correctlyOrientedImage(image: UIImage) -> UIImage {
    if image.imageOrientation == UIImageOrientation.Up {
        return image
    }

    UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale)
    image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
    var normalizedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return normalizedImage;
}

That you can find here https://stackoverflow.com/a/27775741/2364453

Community
  • 1
  • 1
Aminix
  • 158
  • 1
  • 11