How do I save a UIImage to a file?

前端 未结 9 857
抹茶落季
抹茶落季 2020-12-07 13:13

If I have a UIImage from an imagePicker, how can I save it to a subfolder in the documents directory?

相关标签:
9条回答
  • 2020-12-07 13:34

    In Swift 4:

    // Create path.
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    if let filePath = paths.first?.appendingPathComponent("MyImageName.png") {
        // Save image.
        do {
           try UIImagePNGRepresentation(image)?.write(to: filePath, options: .atomic)
        }
        catch {
           // Handle the error
        }
    }
    
    0 讨论(0)
  • 2020-12-07 13:35
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:path atomically:YES];
    

    where path is the name of the file you want to write it to.

    0 讨论(0)
  • 2020-12-07 13:36

    In Swift 3:

    // Create path.
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let filePath = "\(paths[0])/MyImageName.png"
    
    // Save image.
    UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)
    
    0 讨论(0)
提交回复
热议问题