2012-06-04 93 views
2

在我的應用程序中我已經在圖像視圖中設置了圖庫。現在我想將該圖像存儲在我的SQL數據庫中。如何將圖像存儲在我的SQL數據庫中?

  1. 我必須在我的SQL數據庫中更改什麼? (BLOB ??)
  2. 什麼是從圖像視圖中檢索圖像並將其存儲在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); 

     } 
    } 
} 
+0

我的[回覆](http://stackoverflow.com/a/9141116/996493)可能會幫助你。 – Lucifer

回答

3

首先創建這樣的表 db.execSQL(「create table if not exists 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); 

這將retrive圖像從數據庫..

+0

hii你能告訴我什麼是「dbh」SQLiteDatabase db = dbh.getWritableDatabase();在這行。我不明白..plz幫助其真正幫助完整,但我不明白只有這個 – Google

+0

DBH只是SQLiteOpenHelper的對象。我希望你已經將這個類擴展到你的應用程序來創建數據庫和表.. – kalandar

+0

ohkk我明白..是的,我已經擴展了這個類 – Google

2

OR,爲您節省手機存儲器上(SD卡上)的圖像或應用程序緩存等。並且存儲路徑以在SQL數據庫中檢索圖像文件。

+0

我已經嘗試過,但我最終的問題是,您無法將您在圖像視圖中設置的位圖轉換回字符串(圖像路徑)。 – user1420042

+1

我不確定要理解你的意思。 這取決於你選擇你的圖像路徑(使用getExternalCacheDir()+文件名),使用Bitmap.compress函數保存它,然後將它附加到ImageView和ImageView 。 setImageBitmap函數 – VinceFR

2

不是一個好的想法..你應該保存在磁盤上的圖像,以減少SQL操作,並提高應用程序的性能..保存圖像數據庫將使數據庫在各方面沉重..只需將圖像存儲在磁盤上所需的l並在數據庫表中將路徑和圖像名稱一起保存爲字符串。

相關問題