如何将图像放入Realm数据库? [英] How to put an image in a Realm database?

查看:98
本文介绍了如何将图像放入Realm数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift 2编写iOS应用程序,我想在Realm数据库中本地保存帐户的个人资料图片。我找不到任何文件或人们在谈论这个。

I'm writing an iOS application using Swift 2 and I would like to save profile picture of an account locally in a Realm database. I can't find any documentation or people talking about that.

有可能吗?怎么样?

这样做可能不好吗?

推荐答案

您可以将图像存储为 NSData 。如果你有一个图像的URL,你想在本地存储,这里有一个代码片段,如何实现。

You can store images as NSData. Given you have the URL of an image, which you want to store locally, here is a code snippet how that can be achieved.

class MyImageBlob {
    var data: NSData?
}

// Working Example
let url = NSURL(string: "http://images.apple.com/v/home/cb/images/home_evergreen_hero_iphone_medium.jpg")!
if let imgData = NSData(contentsOfURL: url) {
    var myblob = MyImageBlob()
    myblob.data = imgData 

    let realm = try! Realm()
    try! realm.write {
        realm.add(myblob)
    }
}



这样做可能是一个坏主意吗?



规则很简单:
如果图像尺寸小,图像数量很小,它们很少更改,你可以坚持将它们存储在数据库中。

May be it is a bad idea to do that?

The rule is simple: If the images are small in size, the number of images is small and they are rarely changed, you can stick with storing them in the database.

如果有一堆图像,你最好直接将它们写入文件系统只是将图像的路径存储在数据库中。

If there is a bunch images, you are better off writing them directly to the file system and just storing the path of the image in the database.

以下是如何做到这一点:

Here is how that can be done:

class MyImageStorage{
    var imagePath: NSString?
}

let url = NSURL(string: "http://images.apple.com/v/home/cb/images/home_evergreen_hero_iphone_medium.jpg")!
if let imgData = NSData(contentsOfURL: url) {
    // Storing image in documents folder (Swift 2.0+)
    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
    let writePath = documentsPath?.stringByAppendingPathComponent("myimage.jpg")

    imgData.writeToFile(writePath, atomically: true)

    var mystorage = MyImageStorage()
    mystorage.imagePath = writePath

    let realm = try! Realm()
    try! realm.write {
         realm.add(mystorage)
    }
}

请注意:由于存在许多陷阱,因此两种代码示例都不是下载图像的可靠方法。在现实世界的应用程序/生产中,我建议使用专门用于此目的的库,如 AFNetworking AlamofireImage

Please note: Both code samples are not reliable methods for downloading images since there are many pitfalls. In real world apps / in production, I'd suggest to use a library intended for this purpose like AFNetworking or AlamofireImage.

这篇关于如何将图像放入Realm数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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