我有一个简单的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]创建具有未知类型的图像格式是错误”
答案 0 :(得分:2)
请尝试使用此代码我在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)
}
}
答案 1 :(得分:1)
尝试将图像转换为图像数据
let imageCapture = UIImage(data: dataImage)!
UIImageWriteToSavedPhotosAlbum((image: imageCapture), nil, nil, nil)