Android 从 Sqlite 数据库保存和获取图像
Posted
技术标签:
【中文标题】Android 从 Sqlite 数据库保存和获取图像【英文标题】:Android Save And Get Image From Sqlite Database 【发布时间】:2016-06-25 08:49:00 【问题描述】:亲爱的 我如何使用 android Studio 保存图像并从 Sqlite 数据库中获取图像?
【问题讨论】:
将图像转换为 Base 64 字符串,然后将其存储到数据库中,反之亦然。请参阅this 了解 android 中的 Base 64 API。 如果要将二进制文件存储到sqlite中,请将其保存为blob类型。也许这个链接可以帮助你:***.com/questions/7331310/… 【参考方案1】:您可以查看本教程以在 Android 中实现 Sqlite。 http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
例如,您可以使用这种方式来实现,而不是使用联系人
public class Image
String imagePath; //it is your absolute image file path
你的DatabaseHandler
可以像下面这样实现
public class DatabaseHandler extends SQLiteOpenHelper
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "imagedb";
// Contacts table name
private static final String TABLE_IMAGE = "images";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_IMAGE_PATH = "name";
public DatabaseHandler(Context context)
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db)
String sqlQuery = "CREATE TABLE " + TABLE_IMAGE + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE_PATH + " TEXT)";
db.execSQL(sqlQuery);
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGE);
// Create tables again
onCreate(db);
// Adding new image
public void addImage(Image image)
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE_PATH, image.imagePath); // Image path
// Inserting Row
db.insert(TABLE_IMAGE, null, values);
db.close(); // Closing database connection
// Getting single image
public Image getImage(int id)
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_IMAGE, new String[] KEY_ID,
KEY_IMAGE_PATH, KEY_ID + "=?",
new String[] String.valueOf(id) , null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Image image = new Image(Integer.parseInt(cursor.getString(0)),
cursor.getString(1));
// return image
return image;
【讨论】:
我认为他想将整个图像对象存储到数据库中,而不是图像路径。 谢谢@ᖷAЯAƸ。我以为他要的是 sqlite 教程。【参考方案2】:可能为时已晚。但对未来的读者很有用..
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.util.HashMap;
/**
* Created by Noorul on 23-05-2016.
*/
@SuppressWarnings("ALL")
public class DBSplash extends SQLiteOpenHelper
public static final String DATABASE_NAME = "SplashDB.db";
public static final String SPLASH_TABLE_NAME = "splash_db";
private HashMap hp;
public DBSplash(Context context)
super(context, DATABASE_NAME, null, 1);
@Override
public void onCreate(SQLiteDatabase db)
db.execSQL(
"create table " + SPLASH_TABLE_NAME + "( name TEXT, image BLOB)"
);
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
public boolean insertImage(String name, Bitmap img)
Bitmap storedBitmap = null;
String sql = "INSERT INTO " + SPLASH_TABLE_NAME + " (name,image) VALUES(?,?)";
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement insertStmt = db.compileStatement(sql);
byte[] imgByte = getBitmapAsByteArray(img);
try
storedBitmap = getImage(name);
catch (Exception e)
AppLog.exception(e);
if (storedBitmap == null)
insertStmt.bindString(1, name);
insertStmt.bindBlob(2, imgByte);
insertStmt.executeInsert();
db.close();
return true;
public int numberOfRows()
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, SPLASH_TABLE_NAME);
return numRows;
public Bitmap getImage(String name)
String qu = "SELECT * FROM " + SPLASH_TABLE_NAME;
Cursor cur = null;
SQLiteDatabase db = this.getReadableDatabase();
try
cur = db.rawQuery(qu, new String[]);
catch (Exception e)
AppLog.exception(e);
if (cur != null)
if (cur.moveToFirst())
int index = cur.getColumnIndexOrThrow("image");
byte[] imgByte = cur.getBlob(index);
cur.close();
return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
if (cur != null && !cur.isClosed())
cur.close();
return null;
public byte[] getBitmapAsByteArray(Bitmap bitmap)
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, outputStream);
return outputStream.toByteArray();
使用此代码。但是将图像存储在数据库中并不是最佳实践。如果您需要不模糊的图像,请更改图像大小。图像是具有高内存的 blob 类型。移动设备是更小的设备。所以在 sqlite db 中存储许多图像意味着,它会很丑陋。所以使用@thuongle 方法
【讨论】:
以上是关于Android 从 Sqlite 数据库保存和获取图像的主要内容,如果未能解决你的问题,请参考以下文章
从 SQLite 数据库加载的数据未保存在模型类 ArrayList android 中