Original: http://blog.sina.com.cn/s/blog_8cfbb99201012oqn.html
Package Com.yiyiweixiao;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteOpenHelper;
Import Android.database.sqlite.SQLiteDatabase.CursorFactory;
public class Mysqliteopenhelper extends Sqliteopenhelper {
Overriding construction methods
Public Mysqliteopenhelper (Context context, String name,
cursorfactory cursor, int version) {
Super (context, name, cursor, version);
}
Ways to create a database
public void OnCreate (Sqlitedatabase db) {
Create a database, table name: imagetable, field: _id, image.
Db.execsql ("CREATE TABLE imagetable (_id INTEGER PRIMARY KEY autoincrement,image BLOB)");
}
Ways to update a database
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
}
}
Create an instance of the helper class
The value of cursorfactory is null, which means that the default factory class is used
Mysqliteopenhelper = new Mysqliteopenhelper (This, "saveimage.db", null,1);
Create a database that can read and write
MyDB = Mysqliteopenhelper.getwritabledatabase ();
Convert a picture to a bitmap
Bitmap Bitmap1=bitmapfactory.decoderesource (Getresources (), R.drawable.erweima);
int Size=bitmap1.getwidth () *bitmap1.getheight ();
Creates a byte array output stream with the size of the stream
Bytearrayoutputstream baos=new bytearrayoutputstream (size);
Sets the compression format of the bitmap, the mass is 100%, and puts in the byte array output stream bitmap1.compress (Bitmap.CompressFormat.PNG, BAOs);
Serializes the byte array output to a byte array byte[]
Byte[] Imagedata1=baos.tobytearray ();
To save a byte array to the database
Contentvalues cv=new contentvalues ();
Cv.put ("_id", 1);
Cv.put ("image", imagedata1);
Mydb.insert ("imagetable", NULL, CV);
Turn off byte array output stream
Baos.close ();
methods for querying from a database:
Create a pointer
Cursor cur=mydb.query ("ImageTable", New string[]{"_id", "image"}, NULL, NULL, NULL, NULL, NULL);
Byte[] Imagequery=null;
if (Cur.movetonext ()) {
Converts BLOB data to byte array Imagequery=cur.getblob (Cur.getcolumnindex ("image"));
}
Convert a byte array to a bitmap
Bitmap Imagebitmap=bitmapfactory.decodebytearray (imagequery, 0, imagequery.length);
iv1= (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);
To display a bitmap as a picture
Iv1.setimagebitmap (IMAGEBITMAP);
Android SQLite picture Save and read out with stream bytecode