How to Store an Image in Core Data

Can you save an array of images in core data?

convert your array to NSMutableArray and archive it as NSData

var imgArray = [UIImage]();

var CDataArray = NSMutableArray();

for img in imgArray{
let data : NSData = NSData(data: UIImagePNGRepresentation(img))
CDataArray.addObject(data);
}

//convert the Array to NSData
//you can save this in core data
var coreDataObject = NSKeyedArchiver.archivedDataWithRootObject(CDataArray);

after pulling from CData, extract data:

//extract:
if let mySavedData = NSKeyedUnarchiver.unarchiveObjectWithData(coreDataObject) as? NSArray{
//extract data..
}

Swift 5

There are some methods deprecated now. The following code is working in Swift 5:

func coreDataObjectFromImages(images: [UIImage]) -> Data? {
let dataArray = NSMutableArray()

for img in images {
if let data = img.pngData() {
dataArray.add(data)
}
}

return try? NSKeyedArchiver.archivedData(withRootObject: dataArray, requiringSecureCoding: true)
}

func imagesFromCoreData(object: Data?) -> [UIImage]? {
var retVal = [UIImage]()

guard let object = object else { return nil }
if let dataArray = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSArray.self, from: object) {
for data in dataArray {
if let data = data as? Data, let image = UIImage(data: data) {
retVal.append(image)
}
}
}

return retVal
}

saving image with Core Data

For save image in CoreData you must convert the image into DATA type then you can save it into CoreData.This code may useful to save image in CoreData.

@IBOutlet weak var profileimg: UIImageView?

let data = (profileimg?.image)!.pngData()
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Entity", into: context!)
newUser.setValue(data, forKey: "img")

do {
try Constant.context?.save()
}

Make sure the key you enter is correct. Must check box of the Allow External Storage in the Data model Inspector.But I not to recommended to save image in CoreData. Hope this would be helpful.

Sample Image

Swift 3 - Saving images to Core Data

replace

let image: Data = images.value(forKey: "image")! as! Data
let dataDecoded : Data = Data(base64Encoded: image, options: [])!
let decodedimage = UIImage(data: dataDecoded)

with

let image: Data = images.value(forKey: "image")! as! Data
let decodedimage = UIImage(data: image)

Base64 is a way to to convert data to a string. There is no reason to use it here. You already have the data from the database you just want to convert it to a UIImage.

also change

let image = data?.base64EncodedData()
saveImageToDB(brandName: imageBrandName, image: image!)

to

saveImageToDB(brandName: imageBrandName, image: data!)

base64EncodedData is turning the data from image data into a utf-8 encoded based64encoded string. There is no reason for that.

You should get the base64 encoded string from server, convert it to data and then you never need base64 again. Read and write data to your database, and after you read it convert it to a UIImage. Base64 is an encoding method to transfer data. If you are not talking to the server there is no reason to use base64.

How do I save and show a Image with core data - swift 3

The property photo of Users is (NS)Data, as you do there, converting the

UIImage into NSData.

let img = UIImage(named: "f.png")
let imgData = UIImageJPEGRepresentation(img!, 1)
newUser.setValue(imgData, forKey: "photo")

While when you retrieve the info, you are doing like photo was a UIImage object:

if let photoinData = result.value(forKey: "photo") as? UIImage{
imageView.image = photoinData
}

This is not logical according to previous lines. It should be something like that:

if let imageData = result.value(forKey: "photo") as? NSData {
if let image = UIImage(data:imageData) as? UIImage {
imageView.image = image
}
}

Note: I don't speak Swift, so the proposed code may not compile, but you should get the idea of what's wrong and what's need to be done.

Storing images in Core Data or as file?

There are two main options:

  1. Store the file on disk, and then store the path to the image in core data
  2. Store the binary data of the image in core data

I personally prefer the 1st option, since it allows me to choose when I want to load the actual image in memory. It also means that I don't have to remember what format the raw data is in; I can just use the path to alloc/init a new UIImage object.

Storing images to CoreData - Swift

Core Data isn't meant to save big binary files like images. Use Document Directory in file system instead.

Here is sample code to achieve that.

let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String
// self.fileName is whatever the filename that you need to append to base directory here.
let path = documentsDirectory.stringByAppendingPathComponent(self.fileName)
let success = data.writeToFile(path, atomically: true)
if !success { // handle error }

It is recommended to save filename part to core data along with other meta data associated with that image and retrieve from file system every time you need it.

edit: also note that from ios8 onwards, persisting full file url is invalid since sandboxed app-id is dynamically generated. You will need to obtain documentsDirectory dynamically as needed.



Related Topics



Leave a reply



Submit