快速将图像保存到文件并从文件中检索图像

时间:2018-11-28 04:04:57

标签: swift image save

我需要将UIImage保存到文件中。为此,我使用以下代码:


    @IBAction func saveTextImage(_ sender: UIBarButtonItem) {
    let imageToSave = UIImage.imageWithLabel(textField: showRanjana)
    guard let fileURL = TypeRanjanaViewController.storeImageToDocumentDirectory(image: imageToSave, fileName: "Ranjana"+String(currentTimeInMilliSeconds())+".png") else {
        return
    }
    print(fileURL)
    showSavedFile(fileUrlToAshow: fileURL)
    guard let uiImage = UIImage(contentsOfFile: fileURL.absoluteString) else {
        print("Image is nil")
        return
    }
    testImageView.image = uiImage
}

public static func storeImageToDocumentDirectory(image: UIImage, fileName: String) -> URL? {
    guard let data = image.pngData() else {
        return nil
    }
    let fileURL = self.fileURLInDocumentDirectory(fileName)
    do {
        try data.write(to: fileURL)
        return fileURL
    } catch {
        return nil
    }
}
public static var documentsDirectoryURL: URL {
    return FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
}
public static func fileURLInDocumentDirectory(_ fileName: String) -> URL {
    return self.documentsDirectoryURL.appendingPathComponent(fileName)
}

这是从UiLabel检索图像的扩展


extension UIImage {
class func imageWithLabel(textField: UITextField) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(textField.bounds.size, false, 0.0)
    textField.layer.render(in: UIGraphicsGetCurrentContext()!)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return img!
}
}

我能够从uiImage生成图像,并使用saveTextImage(..)函数将其保存。在这里,fileURL返回图像的URL。但是我在创建图像时找不到图像,即它返回nil。我们需要存储/检索图像的权限吗?我们如何从url检索图像/检查图像是否存储到磁盘?

0 个答案:

没有答案