Reputation: 391
I want to save image in Realm but it says that binary is too big. I know that NSData should be less than 16MB. So how can I handle this issue? Anyway to resize NSData?
Upvotes: 0
Views: 1468
Reputation: 1
You can use let imageData = image?.jpegData(compressionQuality: 0.5) which will get your image in Data format and compress the size
Upvotes: 0
Reputation: 21
Had the same problem as well, doing research I fixed my error with help from Realm docs. Here is the link. https://realm.io/docs/tutorials/scanner/#overview.
The helpful code snippet:
func data() -> Data {
var imageData = UIImagePNGRepresentation(self)
// Resize the image if it exceeds the 2MB API limit
if (imageData?.count)! > 2097152 {
let oldSize = self.size
let newSize = CGSize(width: 800, height: oldSize.height / oldSize.width *
800)
let newImage = self.resizeImage(self, size: newSize)
imageData = UIImageJPEGRepresentation(newImage, 0.7)
}
return imageData!
}
To add to Realm, A code can be something like this:
@IBOutlet weak var thumbImg: UIImageView!
let picture = Image()
let imageDownSizing = thumbImg.image?.data()
//thumbImg.image is of type UIImage type, so convert UIImage -> Data.
//picture.image is of type Data.
picture.image = UIImagePNGRepresentation(thumbImg.image!)
picture.image = imageDownSizing
let item = Item()
item.toImage = picture
do{
let realm = try! Realm()
try realm.write {
realm.add(item)
}
}catch{
print("Error saving context \(error)")
}
Upvotes: 2
Reputation: 2251
You can reference parts of the file with NSFileHandle
and it's offsetInFile
method. e.g. in 16MB chunks.
Upvotes: 0