I have 5 Mb worth of images that I want to put into an sqlite db, in blob fields. After the insertion, the db is around 50Mb.
This is how I get the byte[]
:
private static byte[] getByteArrayFromFileName(String filename) {
int id = context.getResources().getIdentifier(filename, "raw", context.getPackageName());
ByteArrayOutputStream blob = new ByteArrayOutputStream();
BitmapFactory.decodeResource(context.getResources(), id).compress(CompressFormat.PNG, 0, blob);
return blob.toByteArray();
}
This is how I insert them into the db:
public void createImage(SQLiteDatabase database, Image image) throws DbException {
ContentValues values = new ContentValues();
values.put(ImageTable.DATA, image.data);
values.put(ImageTable.TYPE_ID, image.type.getValue());
values.put(ImageTable.LEVELID, image.levelId);
values.put(ImageTable.ID, image.id);
if (database.replace(ImageTable.TABLE_NAME, null, values) == -1) {
throw new DbException("createImage insertion error");
}
}
What am I screwing up? :)
edit: the problem was, I should not be putting bitmaps into the database, but just the raw (compressed in jpeg format)files. So for reference, here is a correct way of getting a byte[] from a bitmap file, so it's still small in size:
private static byte[] getByteArrayFromRawByFileName(Context context, String filename) throws IOException {
int id = context.getResources().getIdentifier(filename, "raw", context.getPackageName());
InputStream is = context.getResources().openRawResource(id);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int bytesRead;
byte[] b = new byte[1024];
while ((bytesRead = is.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
return bos.toByteArray();
}