Home > Software design >  SQLite crashes from big image stored in database
SQLite crashes from big image stored in database

Time:09-04

I'm storing images in an SQLite database as bitmap. My code works but when I try to store large pictures (5 megapixels from the built in camera or storage) it crashes and screws up the database so that the app crashes whenever I try to launch it again.

How can I control image size before inserting into database? If the size is > 1 megapixel the apm will show an error message.

CodePudding user response:

Well, the problem is a bit different than what you think -- it's generally a terrible idea to store images (or large blobs in general) inside a relational database (SQL, SQLite, etc). Yes, it's technically allowed, but it's really frowned upon, and causes performance and maintenance issues for the DB. And, of course, there's the issue of it crashing for you when the images get too large...

So, ideally, you should be storing the images on the file system, most likely in your internal app data folder. And then you should have a field in your table that references the file names of the images (and their path if you really want to create some kind of a folder structure). You can then read them from the file system whenever you retrieve the records from the DB.

Having said all that, if you still really insist on storing the images inside the DB, you can resize them pretty easily before you insert them into your DB:

val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, desiredWidth, desiredHeight, true)
  • Related