我目前正在设计一个具有领域的数据库管理应用程序,在那里我已经成功地创建和检索了一个对象。我遇到的问题是更新/编辑-特别是更新用户上传的UIImage。在领域中,我保存图像的路径,然后通过加载该路径(在Directory中)来检索它。
当用户试图保存更改的映像时,由于一些奇怪的原因,UIImageJPEGRepresentation将更改的图像保存为零,从而删除用户的图像。这很奇怪,因为数据对象的最初创建很好地存储了它。
我尝试过通过一些调试来检查映像是否被正确地传递,并且发现它做得非常好,并且正确的路径被保存在上面。
下面是我的更新方法:
func updateImage() {
let documentsDirectoryURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = documentsDirectoryURL.appendingPathComponent("\(selectedPicPath!)")
if FileManager.default.fileExists(atPath: fileURL.path) {
do {
if profilePic.image != nil {
let image = profilePic.image!.generateJPEGRepresentation()
try! image.write(to: fileURL, options: .atomicWrite)
}
} catch {
print(error)
}
} else {
print("Image Not Added")
}
}有人能看到什么问题吗?
发布于 2017-02-25 02:10:38
let image = profilePic.image!.generateJPEGRepresentation()检查这一行,它是返回零值还是数据?如果为零,然后使用下面的代码测试您的图像存储,它是有效的。还要确保您的实际图像具有JPEG文件格式扩展名,这是您正在尝试生成的。
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}//用于PNG图像
if let image = UIImage(named: "example.png") {
if let data = UIImagePNGRepresentation() {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
}用于JPG图像
if let image = UIImage(named: "example.jpg") {
if let data = UIImageJPEGRepresentation(image, 1.0) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.jpg")
try? data.write(to: filename)
}
}https://stackoverflow.com/questions/42451053
复制相似问题