亲爱的 我如何使用 Android Studio 保存图像并从 Sqlite 数据库获取图像?
最佳答案
可能为时已晚。但对 future 的读者有用..
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 方法
关于java - Android 从 Sqlite 数据库中保存并获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35917673/