android sqlite 选择、存储、读取图片完整代码示例
时间: 2023-08-15 09:03:24 浏览: 36
以下是一个完整的Android SQLite选择、存储、读取图片的示例代码:
```java
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "images.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE images (_id INTEGER PRIMARY KEY AUTOINCREMENT, image BLOB)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS images");
onCreate(db);
}
public void insertImage(Bitmap bitmap) {
byte[] imageBytes = getBytesFromBitmap(bitmap);
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("image", imageBytes);
db.insert("images", null, values);
db.close();
}
public Bitmap getImage(int id) {
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[] { "image" };
String whereClause = "_id=?";
String[] whereArgs = new String[] { String.valueOf(id) };
Cursor cursor = db.query("images", columns, whereClause, whereArgs, null, null, null);
if (cursor.moveToFirst()) {
byte[] imageBytes = cursor.getBlob(0);
cursor.close();
db.close();
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
}
cursor.close();
db.close();
return null;
}
public List<Integer> getAllIds() {
List<Integer> ids = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] columns = new String[] { "_id" };
Cursor cursor = db.query("images", columns, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
ids.add(id);
}
cursor.close();
db.close();
return ids;
}
private static byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
}
```
使用示例:
```java
// 将图片插入到数据库中
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image);
DBHelper dbHelper = new DBHelper(this);
dbHelper.insertImage(bitmap);
// 从数据库中读取图片
int id = 1;
Bitmap image = dbHelper.getImage(id);
// 获取所有图片的ID
List<Integer> ids = dbHelper.getAllIds();
```