在Swift(iOS)中保存图像并加载它

59

我正在使用saveImage保存一张图片。

func saveImage (image: UIImage, path: String ) -> Bool{

    let pngImageData = UIImagePNGRepresentation(image)
    //let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG

    print("!!!saving image at:  \(path)")

    let result = pngImageData!.writeToFile(path, atomically: true)

    return result
}

最新信息:

保存文件无法正常工作(会打印出“[-] ERROR SAVING FILE”)--

            // save your image here into Document Directory
        let res = saveImage(tempImage, path: fileInDocumentsDirectory("abc.png"))
        if(res == true){
            print ("[+] FILE SAVED")
        }else{
            print ("[-] ERROR SAVING FILE")
        }

为什么saveImage函数不能保存图像?是访问权限的问题吗?

旧信息:

调试信息如下:

!!!saving image at:  file:///var/mobile/Applications/BDB992FB-E378-4719-B7B7-E9A364EEE54B/Documents/tempImage

然后我使用以下方法检索这个位置

fileInDocumentsDirectory("tempImage")

结果是正确的。

然后,我正在使用这个路径加载文件

    let image = UIImage(contentsOfFile: path)

    if image == nil {

        print("missing image at: \(path)")
    }else{
        print("!!!IMAGE FOUND at: \(path)")
    }

路径是正确的,但是显示“缺少图片...”。这个文件是否无法访问或未存储?造成这种行为的原因是什么?

我正在使用iOS 7上的iPhone 4和iOS 7模拟器上的iPhone 5进行测试。

编辑: 1. fileInDocumentsDirectory函数。

func fileInDocumentsDirectory(filename: String) -> String {

    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let fileURL = documentsURL.URLByAppendingPathComponent(filename).absoluteString
    return fileURL        
}

检查Finder中是否有该图像,并将一些扩展名添加到图像*.png或*.jpeg。 - Ashish Kakkad
不要保存图像的完整路径,只保存图像名称,并将名称附加到实时文档目录路径。这样做是因为每次运行时文档目录路径都不相同。 - Nitin Gohel
@NitinGohel 我只是保存文件,然后尝试像这样加载它 loadImageFromPath(fileInDocumentsDirectory("abc.png"))。 - tesgoe
fineInDocumentDirectory是实时路径还是从数据库加载的? - Nitin Gohel
@Joakim 谢谢。看起来我想要使用“文档”目录,因为我正在存储用户个人资料图片。 - tesgoe
显示剩余4条评论
11个回答

0

我一段时间前在StackOverFlow上找到了解决方案,但我不记得作者是谁了。

假设yourImage是UIImage()

let ciImage = yourImage!.ciImage
let context = CIContext()
let cgImage = context.createCGImage(ciImage!, from: ciImage!.extent)
let uiImage = UIImage(cgImage: cgImage!)

UIImageWriteToSavedPhotosAlbum(uiImage, self, 
#selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)

和这个函数

@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
    // we got back an error!
    let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
    ac.addAction(UIAlertAction(title: "OK", style: .default))
    present(ac, animated: true)
} else {
    let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
    ac.addAction(UIAlertAction(title: "OK", style: .default))
    present(ac, animated: true)
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接