Reputation: 23
In my app, I have a button with which I open the Gallery as below:
@IBAction func selectPhoto() {
let photoPicker = UIImagePickerController()
photoPicker.delegate = self
photoPicker.sourceType = .PhotoLibrary
self.presentViewController(photoPicker, animated: true, completion: nil)
}
I let the user select a photo and save it:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
photoImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
let fileName:String = "logo.png"
let arrayPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let pngFileName = arrayPaths.stringByAppendingPathComponent(fileName) UIImagePNGRepresentation(photoImageView.image!)!.writeToFile(pngFileName, atomically:true)
imageSave.setObject(fileName, forKey: "pngFileName")
self.dismissViewControllerAnimated(false, completion: nil)
}
Then from View controller, the pictures saved is shown everytime the user gets to the scene using below code.
override func viewDidLoad() {
super.viewDidLoad()
if imageSave.stringForKey("pngFileName") != nil
{
let path = NSSearchPathForDirectoriesInDomains(
.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let fileName = NSUserDefaults.standardUserDefaults()
.stringForKey("pngFileName")
let imagePath = path.stringByAppendingPathComponent(fileName!)
let image = UIImage(contentsOfFile: imagePath )
photoImageView.image = image
}
Problem : When the image loads back onto the UIImageView, the orientation of the picture is sometimes rotated right by 90 degrees, sometimes rotated left by 90 degrees or sometimes shown as it was saved.
Please let me know what I am doing wrong here. Any help would be appreciated. Thanks
Upvotes: 2
Views: 1404
Reputation: 323
I had the same problem, because of different rect sizes where the photo is shown. You could do a trick and save instead of the original image a copied version. This will discard the rotation problem, which is actually a fitting issue.
let imageName = info[UIImagePickerControllerOriginalImage] as! UIImage
let thumb1 = UIImageJPEGRepresentation(imageName, 0.8)
btnImageView.image = UIImage(data: thumb1!)
This is just a quick and dirty answer, but worked for me. :-)
Upvotes: 2