如何将图像写入文件?

时间:2017-02-18 18:42:23

标签: swift swift3 uiimage

我正在使用Swift 3,Xcode 8.2,iOS 10

出于调试目的,我正在尝试拍摄图像,裁剪图像并显示裁剪后的图像。我正在尝试将此图像写入我的计算机(Mac OS X)桌面,但我发现的所有教程都将我写入我的文档目录,我错误地认为它实际上是我计算机上的一个目录,但结果却是& #39;手机本身的这个位置,我无法弄清楚如何访问。

到目前为止,我有这个:

    let finalImage : UIImage

    let crop_section = CGRect(x: 0.0, y: 0.0, width: 1000.0, height: 1000.0)

    let cg_image = screenshot.cgImage?.cropping(to: crop_section)
    finalImage = UIImage(cgImage: cg_image!)

    let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    // create a name for your image
    print(documentsDirectoryURL)
    let fileURL = documentsDirectoryURL.appendingPathComponent("cropped.png")


    if !FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try UIImagePNGRepresentation(finalImage)!.write(to: fileURL)
            print("Image Added Successfully")
        } catch {
            print(error)
        }
    } else {
        print("Image Not Added")
    }

我想用documentDirectory之类的内容替换../Desktop/cropped.png,但我无法弄清楚如何执行此操作。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

  

我想用../Desktop/cropped.png

之类的东西替换documentDirectory

你不能。这是一个iOS程序。 iOS应用程序在iOS设备/模拟器上的自己的目录集中沙箱化;它无法触及并看到Mac OS X桌面。它们是两个不同的宇宙。