简体   繁体   English

在iOS的SQLite中检索和存储图像

[英]Retrieving and Storing images in SQLite in ios

How can we create a button to store and retrieve images in sqlite in ios application? 我们如何在iOS应用程序中创建一个按钮以在sqlite中存储和检索图像? Actually I am building a Application in which i can take photo from camera and I have to store it and display as a profile picture 实际上,我正在构建一个应用程序,可以在其中从相机拍摄照片,我必须将其存储并显示为个人资料图片

Storing image data in database is not proper way if you want to store large number of images. 如果要存储大量图像,将图像数据存储在数据库中是不合适的方法。 It will hang the UI. 它将挂起UI。

You can make a folder in Document Directory and put the image there. 您可以在“文档目录”中创建文件夹,然后将图像放在此处。 So, you will get image from there only every time. 因此,您每次都只能从那里获得图像。

In the database, store the file-path and get the image from that file path. 在数据库中,存储文件路径并从该文件路径获取图像。

Be sure to remove the images from Document Directory, once it becomes unusable ie user changes the profile picture. 一旦无法使用,即用户更改个人资料图片,请确保从“文档目录”中删除图像。 Otherwise, it will continuously increase your App's memory. 否则,它将不断增加您应用程序的内存。

Better to store the image at file path which is your document directory and store the file path in sqlite for faster access of the image. 最好将图像存储在文件路径(即文档目录)中,并将文件路径存储在sqlite中,以便更快地访问图像。

Make a file path as below: 制作如下文件路径:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);  
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory 
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file

Now filepath string will insert into your sqlite database. 现在,文件路径字符串将插入到您的sqlite数据库中。

and now when you access the image you will get file path from the sqlite and get image data from that like below: 现在,当您访问图像时,将从sqlite获取文件路径,并从如下所示获取图像数据:

NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *image = [UIImage imageWithData:pngData];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM