Swift 3.0将映像写入目录 [英] Swift 3.0 writing Image to Directory
本文介绍了Swift 3.0将映像写入目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的 ImagePicker
供用户选择或拍摄个人资料照片.我想将此 image
保存到 Home
Directory
中,以便以后加载.
I have a simple ImagePicker
for the user to select, or take, a profile picture. I want to save this image
to the Home
Directory
for easy loading later.
问题在于未设置图像类型.
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)
}
确切的错误是:
"[通用]使用未知类型创建图像格式是错误的"
"[Generic] Creating an image format with an unknown type is an error"
推荐答案
请尝试使用此代码,我在swift 2.2中使用它.下面的方法同时包含UIImageJPEGRepresentation,UIImagePNGRepresentation
Please try this code i am using it in swift 2.2. Below method includes for both 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)
}
}
这篇关于Swift 3.0将映像写入目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文