Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save image in Realm

Tags:

swift

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

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'

What i'm doing wrong?

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);
}
like image 958
Lion Gurman Avatar asked Oct 20 '16 11:10

Lion Gurman


People also ask

Can we store image in realm?

Along with text, MongoDB Realm allows developers to upload images to a local Realm database. You can either upload the image to an open-source image uploader, like Imgur, and then download it back to cache it, or you can store the image locally in your Realm database.

How do I backup my World in Minecraft Realms?

Select the “Upload” button and your local world save will be uploaded to your Minecraft Realms server. Set that world map as the current one and then hop right back into the world and resume play as if it was the day you backed the map up. › Buying a Used Mac or MacBook?

How do I download a copy of the world from realms?

If you want a copy of the world from your Realms server on your local PC, either for archival purposes or for playing offline, you can download it easily. Make sure the world you wish to back up is the active world. For demonstration purposes we’re downloading “World 1” which, as seen in the screenshot above, is the currently loaded world.

How do I restore my realm in Minecraft?

How to Restore Your Minecraft Realm. Just like there are two ways to back up your Minecraft Realms world, there are two ways to restore it. You can restore your worlds from server-side backups (which is a single click affair and can be performed even if you have no local backups) or from saves located on your local computer.

How to save images locally using userdefaults and file system?

We will be using UserDefaults and file system in order to save locally. To get started we will start by writing the foundational code and then later on we will add the implementation code for each method of saving the images. Let's start by creating the StorageType enum. This enum will have two cases, userDefaults and fileSystem.


2 Answers

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
    }
like image 52
Peter Pohlmann Avatar answered Oct 21 '22 06:10

Peter Pohlmann


https://realm.io/docs/objc/latest/#current-limitations maximum data size is 16 MB . this is limitation of realm

like image 24
Vyacheslav Avatar answered Oct 21 '22 05:10

Vyacheslav