Reputation: 53
I try to save a picture into the database as a BLOB, but its not stored properly in the database.
The byte[] which is passed is correct and has 4300 characters and in the database it just has 12 characters. That's what is stored in the DB: [B@43e7be68
Here is the code of my SQL_INSERT:
public boolean SQL_INSERT_PICTURE(PictureDatatype type) {
try{
this.db = openHelper.getWritableDatabase();
Log.d(TAG, "Insert picture");
System.out.println("insert picture");
db.execSQL("DELETE FROM picture " +
"where " + LinkPic + " = '" + type.getLink() + "'");
db.execSQL("INSERT OR REPLACE INTO picture " +
"( " + NamePic + ", " + LinkPic + ", " + PicturePic + ") " +
"VALUES ('" + type.getName() + "', '" + type.getLink() +"', '" +
type.getPicture() +"')");
System.out.println("size of the picture (bytearray): " + type.getPicture().length);
System.out.println("the picture: " + type.getPicture());
System.out.println("insert complete");
db.close();
return true;
}
catch(SQLException s){
System.out.println("Insert failed");
db.close();
return false;
}
}
my question is why isn't the correct byte[] stored in the DB or how can i do it? If u need more information or code pls tell me.
thx kirbby
Upvotes: 1
Views: 1329
Reputation: 7915
Use this code to convert the image to a ByteArray that can be stored as a BLOB:
private byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// Middle value is quality, but PNG is lossless, so it's ignored.
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
OR
private byte[] getBitmapAsByteArray(Bitmap bitmap) {
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(width * height * 4);
bitmap.copyPixelsToBuffer(byteBuffer);
return byteBuffer.array();
}
First option should always work. Second option assumes 32bits-per-pixel (ARGB_8888 format) thus 4 bytes. if you're bitmap is of another format (e.g 565), it needs some modifications.
When you read the image data from the database, do it like this:
public Bitmap loadIcon(long iconId) {
// Prepare the cursor to read from database....
byte[] bitmapData = cursor.getBlob(cursor.getColumnIndex(Columns.Icons.DATA));
return BitmapFactory.decodeByteArray(bitmapData, 0, bitmapData.length);
}
Make sure that the the database is defined as BLOB when you execute your "create table" SQL statement.
Upvotes: 1
Reputation: 13632
Ouch, that looks like you're trying to pass a byte[] array into a string.
Assembling your SQL strings in this way is a very bad idea, for multiple reasons (security and performance).
See these two questions for prepared statements, and how to bind values to the statement without having to concatenate your SQL:
insert a picture into database(sqlite) with java code. what should i do?
Java Exception Error - Sqlite preparedStatement.setBlob
Upvotes: 0