【问题标题】:Swift 3.0 writing Image to DirectorySwift 3.0 将图像写入目录
【发布时间】:2016-10-06 12:38:08
【问题描述】:

我有一个简单的ImagePicker 供用户选择或拍摄个人资料照片。我想将这个image 保存到Home Directory 以便以后加载。

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

    //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)
    }

确切的错误是:

"[Generic] 创建未知类型的图像格式是错误的"

【问题讨论】:

    标签: ios iphone swift xcode swift3


    【解决方案1】:

    请尝试此代码,我在 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)
        }
    }
    

    【讨论】:

    • UIImage 的值没有成员'write'
    • @user1514436 'write' 方法可用于 NSData 而不是 UIImage,您可能正在 UIImage 上使用 write 函数
    • 它不会让我在 UIImage 上使用它。我认为我的代码中缺少其他内容...
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 2016-11-06
      • 2016-09-07
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多