在Realm中保存图像

时间:2016-10-20 11:04:33

标签: swift realm

我试图通过方法从设备的照片库中选择图片:

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

构建成功后尝试选择并保存图像(在应用程序中)我有应用程序错误: ' Binary太大'

我做错了什么?

P.S。对不起我的英文:)

经过一些动作后,我有了这段代码。但它覆盖了我的形象。

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

3 个答案:

答案 0 :(得分:9)

不要将图像本身保存到域中,只需将图像的位置保存为字符串或NSString,然后从该保存的路径加载图像。性能方面,从该物理位置加载图像总是更好,而且数据库不会太大

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

        let image = UIImage(contentsOfFile: path as String)

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

或者您只需保存图像名称,如果它在您的文档目录中无论如何

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    
    }

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

    @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
    }

答案 1 :(得分:1)

https://realm.io/docs/objc/latest/#current-limitations 最大数据大小为16 MB。这是领域的限制

答案 2 :(得分:0)

根据您对图像数据进行序列化的方式(例如,如果它是无损位图),这个数据很可能超过16MB,正如您所说的那样,Realm' s二进制属性支持的最大大小。

当您调用NSData.length时,它的数据有多大?