Search code examples
swiftcore-data

Resize image before saving to Core Data


What's typically the process to resize an image before saving it to Core Data?

I would like to be able to resize an image to 75px75p before saving it to Core Data to minimize its size. The image can come directly from the Photos library or the camera. I have a feeling that the way I'm currently saving it, it's saving a huge file size where in reality I only need a thumbnail image (75x75).

Here is how I'm currently saving it.

Core Data Object: Item

Attribute: image: Binary Data

// image is passed to the addItem function directly from an Image Picker
func addItem(name:String, image:UIImage?){
    if let image = image {
        imageData = image.jpegData(compressionQuality: 0.1)!
    }else{
        imageData = nil
    }
    item.name = name
    item.image = imageData
    self.manager.save()
}

Any advice would be greatly appreciated.


Solution

  • All you need to do is scale the image before getting the JPEG data.

    func addItem(name: String, image: UIImage?) {
        let size = CGSize(width: 75, height: 75)
        var imageData: Data? = nil
        if let thumb = image?.preparingThumbnail(of: size) {
            imageData = thumb.jpegData(compressionQuality: 1.0)
        }
    
        item.name = name
        item.image = imageData
        self.manager.save()
    }
    

    Note that preparingThumbnail(of:) does requires iOS 15.0 or later.