在我的应用程序中,我有一个按钮,用于打开图库,如下所示:
@IBAction func selectPhoto() {
let photoPicker = UIImagePickerController()
photoPicker.delegate = self
photoPicker.sourceType = .PhotoLibrary
self.presentViewController(photoPicker, animated: true, completion: nil)
}
我让用户选择一张照片并保存:
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)
}
然后在View控制器中,每次用户使用以下代码到达场景时,都会显示保存的图片。
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
}
问题:当图像加载回UIImageView时,图片的方向有时会向右旋转90度,有时会向左旋转90度,或者有时会在保存时显示。
请告诉我这里我做错了什么。任何帮助,将不胜感激。感谢
答案 0 :(得分:0)
我遇到了同样的问题,因为照片显示的矩形大小不同。你可以做一个技巧,而不是原始图像保存复制版本。这将丢弃旋转问题,这实际上是一个合适的问题。
let imageName = info[UIImagePickerControllerOriginalImage] as! UIImage
let thumb1 = UIImageJPEGRepresentation(imageName, 0.8)
btnImageView.image = UIImage(data: thumb1!)
这只是一个快速而肮脏的答案,但对我有用。 : - )