[英]How can I store an image in my SQL database?
在我的應用程序中,我已在圖像視圖中從圖庫中設置了圖像。 現在,我想將該圖像存儲在SQL數據庫中。
這是我的SQL數據庫:
private static final String DATABASE_CREATE =
"create table " + DATABASE_TABLE + " ("
+ KEY_ROWID + " integer primary key autoincrement, "
+ KEY_TITLE + " text not null, "
+ KEY_BODY + " text not null, "
+ KEY_DATE_TIME + " text not null);";
在這里,我獲得了圖像在圖庫中的路徑,然后在圖像視圖中設置了圖像
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PICK_FROM_FILE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Log.v("IMAGE PATH====>>>> ",selectedImagePath);
// Decode, scale and set the image.
Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, NEW_WIDTH, NEW_HEIGHT, true);
myBitmap.recycle();
myBitmap = null;
mImageView.setImageBitmap(scaledBitmap);
}
}
}
首先創建這樣的表db.execSQL(“如果不存在則創建表tablename(....,images BLOB,.....);”);
然后像這樣做你的java代碼,
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Bitmap bit = BitmapFactory.decodeFile("your image path here");
bit.compress(CompressFormat.PNG, 0, outputStream);
SQLiteDatabase db = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
..
cv.put("images", outputStream.toByteArray());
..
..
db.insert("tablename", null, cv);
db.close();
這會將您的圖像存儲到數據庫,
byte []temp = c.getBlob(3);
Bitmap image = BitmapFactory.decodeByteArray(temp, 0, temp.length);
BitmapDrawable dd = new BitmapDrawable(image.getImage());
imgView.setBackgroundDrawable(dd);
這將從數據庫中檢索圖像。
或者,將圖像保存在手機內存(SD卡上)或應用程序緩存等中。然后在SQL數據庫中存儲用於檢索圖像文件的路徑。
這不是一個好主意。您應該將映像保存在磁盤上,以減少sql操作並提高應用程序性能。.在DB中保存映像將在各種意義上使數據庫變重。.只需將映像存儲在磁盤上的所需位置並保存路徑以及圖像名稱作為數據庫表中的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.