在Realm中保存图像 [英] Save image in Realm

查看:91
本文介绍了在Realm中保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下方法从设备的图片库中选取图片:

I'm trying to pick image from device's Photo Library in method:

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):

and save this picture in Realm (as NSData):

asset.assetImage = UIImagePNGRepresentation(userPhoto.image!)! as NSData?

...

   try! myRealm.write
        {
            user.assetsList.append(asset)
            myRealm.add(user)
        }

构建成功并尝试选择并保存图像(在应用程序中)后,我遇到了应用程序错误: 二进制太大"

After build succeeded and trying to pick and save image (in the app) i have app error: 'Binary too big'

我做错了什么?

P.S.对不起,我的英语:)

P.S. Sorry for my English :)

经过一些操作,我得到了这段代码.但这会覆盖我的图片.

After some actions i have this code. But it's overwrite my image.

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

推荐答案

不要将图像本身保存到领域中,只需将图像的位置保存为String或NSString到领域中,然后从该保存的路径加载图像.从性能角度来看,最好始终从该物理位置加载图像,并且数据库不会太大

Don't save the image itself into realm, just save the location of the image into realm as String or NSString and load the image from that saved path. Performance wise it's always better to load images from that physical location and your database doesn't get too big

  func loadImageFromPath(_ path: NSString) -> UIImage? {

        let image = UIImage(contentsOfFile: path as String)

        if image == nil {
            return UIImage()
        } else{
            return image
        }
    }

或者,只要您将图像名称保存在文档目录中,就可以保存

or you just save the image name, if it's in your documents directory anyhow

func loadImageFromName(_ imgName: String) -> UIImage? {

        guard  imgName.characters.count > 0 else {
            print("ERROR: No image name")
            return UIImage()
        }

        let imgPath = Utils.getDocumentsDirectory().appendingPathComponent(imgName)
        let image = ImageUtils.loadImageFromPath(imgPath as NSString)           
        return image    
    }

下面是一个粗略的示例,说明如何使用唯一名称将捕获的图像保存到您的目录中:

and here a rough example how to save a captured image to your directory with a unique name:

    @IBAction func capture(_ sender: AnyObject) {

        let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
            stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (imageDataSampleBuffer, error) -> Void in

                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                //self.stillImage = UIImage(data: imageData!)
                //self.savedImage.image = self.stillImage

                let timestampFilename = String(Int(Date().timeIntervalSince1970)) + "someName.png"

                let filenamePath =  URL(fileReferenceLiteralResourceName: getDocumentsDirectory().appendingPathComponent(timestampFilename))
                let imgData = try! imageData?.write(to: filenamePath, options: [])

            })



    /* helper get Document Directory */
    class func getDocumentsDirectory() -> NSString {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentsDirectory = paths[0]
        //print("Path: \(documentsDirectory)")
        return documentsDirectory as NSString
    }

这篇关于在Realm中保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆