【发布时间】:2016-10-20 11:04:32
【问题描述】:
我正在尝试从设备的照片库中选择图片的方法:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
userPhoto.image = info[UIImagePickerControllerOriginalImage] as! UIImage?
userPhoto.contentMode = .scaleAspectFill
userPhoto.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
并将这张图片保存在 Realm 中(作为 NSData):
asset.assetImage = UIImagePNGRepresentation(userPhoto.image!)! as NSData?
...
try! myRealm.write
{
user.assetsList.append(asset)
myRealm.add(user)
}
构建成功并尝试选择并保存图像(在应用程序中)后,我遇到应用程序错误: '二进制太大'
我做错了什么?
附:对不起我的英语:)
经过一些操作后,我得到了这段代码。但它会覆盖我的图像。
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
userPhoto.image = image
userPhoto.contentMode = .scaleAspectFill
userPhoto.clipsToBounds = true
urlCatch = (localPath?.path)!
self.dismiss(animated: true, completion: nil);
}
【问题讨论】:
-
调试并打印你的 imageName let imageName = imageUrl.lastPathComponent 如果它总是同名,则图像被覆盖。图像名称必须是唯一的。类似于 let timestampFilename = String(Int(Date().timeIntervalSince1970)) + "_newImage.png"
-
效果很好!非常感谢!