gpt4 book ai didi

ios - 将图库中的图像保存到 iOS 应用程序

转载 作者:行者123 更新时间:2023-11-28 12:47:15 25 4
gpt4 key购买 nike

我是 Swift 的新手,我正在尝试将手机(或互联网)图库中的图像保存到我的应用程序中。我发现许多教程展示了如何查看图像,但没有展示如何将其保存到我的应用程序(我猜是我的 Assets 文件夹)并在以后使用它。有人可以告诉我正确的方向吗?

最佳答案

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

}

以下是稍后在您的代码中使用该函数的方法:

saveImage(image, path: imagePath)

但是,在保存或加载任何内容之前,您必须知道要使用的“路径”。我们需要 3 样东西:

  • 精确定位文档目录的功能
  • documents目录下的一个文件一个函数来精确定位
  • 一个变量来存储我们要保存的图像的位置(路径)

下面是我们将如何做到这一点:

    func getDocumentsURL() -> NSURL {
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
return documentsURL
}

func fileInDocumentsDirectory(filename: String) -> String {

let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
return fileURL.path!

}

// Define the specific path, image name
let imagePath = fileInDocumentsDirectory(myImageName)

访问更多:http://helpmecodeswift.com/image-manipulation/saving-loading-images

关于ios - 将图库中的图像保存到 iOS 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37664570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com