ios - 如何保存使用 UIImagePickerController 相机拍摄的照片以便稍后在应用程序中显示?

标签 ios iphone xcode swift camera

我让用户使用 UIImagePickerController 拍照,我需要将它保存到应用程序中,以便在他们以后需要查看时显示。我怎样才能做到这一点?

我听说 NSUserDefaults 是个错误。我只需要保存一张图片,再也不需要保存了。

最佳答案

这是将图片保存到文件夹的功能

func saveImage (image: UIImage, path: String ) -> Bool{
        let pngImageData = UIImagePNGRepresentation(image)
         //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
        let result = pngImageData.writeToFile(path, atomically: true)
        return result
    }

这是获取带有图像名称的文档目录路径的函数

func fileInDocumentsDirectory(filename: String) -> String {
    let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
    return documentsFolderPath.stringByAppendingPathComponent(filename)
}

这是一个如何使用图片路径的例子

let imagePath = fileInDocumentsDirectory(myImageName)

这是将图像保存到该文件夹​​的方法

saveImage(image, path: imagePath)

现在最后一部分是获取你的图像,所以使用这个函数来获取你的图像

func loadImageFromPath(path: String) -> UIImage? {
    let image = UIImage(contentsOfFile: path)
    if image == nil {
        println("Image not available at: (path)")
    }
    return image
}

下面是你如何使用上面的函数

image = loadImageFromPath(imagePath)
imageView.image = image

希望对你有帮助

关于ios - 如何保存使用 UIImagePickerController 相机拍摄的照片以便稍后在应用程序中显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32184619/

相关文章:

iphone - 允许用户通过点击选择 UIPickerView 行

xcode - 有没有办法在 Xcode 8.1 中模拟 2016 MacBook Pro Touch Bar?

ios - 苹果的错误响应是否识别无效 token ?

ios - Collectionview.reloaddata() 之后无法选择 UICollectionViewcell

iphone - UIGestureRecognizer 在 UIScrollView 减速期间未接收到触摸

c++ - 如何在带有 xcode 的 objective-c 项目中使用我的自定义类型 (C++)?

ios - 动态访问变量

ios - 如何为YCbCr图像创建vImage_CGImageFormat?

ios - 我无法使用自动布局

iphone - UISearchBar - 搜索对象数组的 NSDictionary