iOS:UIImagePNGRepresentation()。writeToFile未写入预期目录

3

我正在使用 Swift 尝试从URL下载一个 JPG 图像,然后将该图像保存到文件中,但是当我尝试将其保存到另一个子文件夹时,它无法保存。它可以下载到应用程序的 Documents 文件夹,但是当我尝试将路径设置为另一个子文件夹时,它不行。

let dir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0].stringByAppendingPathComponent("SubDirectory") as String
let filepath = dir.stringByAppendingPathComponent("test.jpg")
UIImagePNGRepresentation(UIImage(data: data)).writeToFile(filepath, atomically: true)

当我运行这段代码时,它为什么没有保存图片呢?这是为什么?我需要提前创建子文件夹吗?

1个回答

7
一些想法:

  1. Does the subdirectory folder already exist? If not, you have to create it first. And it's now advisable to use NSURL instead of path strings. So that yields:

    let filename = "test.jpg"
    let subfolder = "SubDirectory"
    
    do {
        let fileManager = NSFileManager.defaultManager()
        let documentsURL = try fileManager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
        let folderURL = documentsURL.URLByAppendingPathComponent(subfolder)
        if !folderURL.checkPromisedItemIsReachableAndReturnError(nil) {
            try fileManager.createDirectoryAtURL(folderURL, withIntermediateDirectories: true, attributes: nil)
        }
        let fileURL = folderURL.URLByAppendingPathComponent(filename)
    
        try imageData.writeToURL(fileURL, options: .AtomicWrite)
    } catch {
        print(error)
    }
    
  2. I would advise against converting the NSData to a UIImage, and then converting it back to a NSData. You can just write the original NSData object directly if you want.

    The process of round-tripping this through a UIImage can make lose quality and/or metadata, potentially making the resulting asset larger, etc. One should generally use the original NSData where possible.


谢谢!这解释了很多问题。你的代码非常有帮助。我将转换为一个Image的原因是,如果文件系统中没有这个图片,我会下载它并加载到一个ImageView中。 - The Nomad
1
如果您需要UIImage进行其他操作,请随意实例化。我只是建议您不要在没有充分理由的情况下再次以PNG格式提取NSData,因为:(a)这会更慢;(b)文件可能会更大(特别是原始图像为JPEG时);(c)您正在剥离元数据等。如果您真的想/需要进行PNG转换,请确保您有充分的理由这样做。 - Rob
已经注意到了。可以理解。如果不必要的话,不将数据转换是有道理的。我在代码中进行了调整,将NSData保存到文件时仍保持为NSData。但在显示时确实需要将其转换为UIImage。感谢您的帮助! - The Nomad

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