xcode Swift 3.0 将图像写入目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39896245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 09:24:40  来源:igfitidea点击:

Swift 3.0 writing Image to Directory

iosiphoneswiftxcodeswift3

提问by Thegasman2000

I have a simple ImagePickerfor the user to select, or take, a profile picture. I want to save this imageto the HomeDirectoryfor easy loading later.

我有一个简单的方法ImagePicker供用户选择或拍摄个人资料图片。我想将其保存imageHomeDirectory以便以后轻松加载。

The problem is with the Image type not being set.

问题在于未设置图像类型。

    //Save Image
    _ = PPimagePicked.image
    let imageData = UIImageJPEGRepresentation(PPimagePicked.image!, 0.6)
    let compressedJPGImage = UIImage(data: imageData!)
    UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil)
    // Get Document Root Path
    let path = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/profile.jpg")
    do {
        //Save image to Root
        try imageData?.write(to: path, options:  .atomic)
        print("Saved To Root")
    } catch let error {
        print(error)
    }

The exact Error is :

确切的错误是:

"[Generic] Creating an image format with an unknown type is an error"

“[通用] 使用未知类型创建图像格式是错误的”

回答by Parth Adroja

Please try this code i am using it in swift 2.2. Below method includes for both UIImageJPEGRepresentation, UIImagePNGRepresentation

请试试这个代码,我在 swift 2.2 中使用它。下面的方法包括 UIImageJPEGRepresentation,UIImagePNGRepresentation

if let image = UIImage(named: "example.png") {
    if let data = UIImageJPEGRepresentation(image, 0.8) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

if let image = UIImage(named: "example.png") {
    if let data = UIImagePNGRepresentation(image) {
        let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
        try? data.write(to: filename)
    }
}

回答by neprocker

try converting the image to image data

尝试将图像转换为图像数据

       let imageCapture = UIImage(data: dataImage)!
        UIImageWriteToSavedPhotosAlbum((image: imageCapture), nil, nil, nil)