2012-03-16 24 views
2

我正在使用以下代碼:請注意,我必須使用此過程發送SQL查詢。正在保存使用sql查詢方法的圖像

currentReceipt.imagebyte[]

 String updateQuery = "INSERT INTO MAReceipts(userId, transactionId, transactionType, receiptIndex, referenceNo, image, smallThumb, comments, createdOn, updatedOn) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; 

     java.util.Date today = new java.util.Date(); 
    long t = today.getTime(); 
    java.sql.Date now = new java.sql.Date(t); 

    for(int i = 0; i < receipts.size(); i++) 
     { 
     try{ 
     Receipt currentReceipt = receipts.get(i); 
      String[] valVars = { 
        stringToDB(transaction.userId), 
        integerToDB(transaction.transactionId), 
        integerToDB(transaction.transactionType.getValue()), 
        integerToDB(i), 
        stringToDB(currentReceipt.referenceNo), 
        (currentReceipt.image != null ? imageToDB(currentReceipt.image): "null"), 
        (currentReceipt.smallThumb != null ? imageToDB(currentReceipt.smallThumb): "null"), // NEED TO CHANGE THIS TO SMALL THUMB 
        stringToDB(currentReceipt.comments), 
        dateToDB(now), 
        dateToDB(now) 
        }; 

      mDb.execSQL(updateQuery, valVars); 
     }catch (Exception e){ 
      Log.e("Error in transaction", e.toString()); 
      return false; 
      } 
     } 


public String imageToDB (byte[] image) 
    { 
     String convertedImage = image.toString(); 
     return convertedImage; 
    } 

return convertedImage示出的[[email protected]的值或相似。

現在這些數據保存在數據庫中。請告訴我圖像正確保存在數據庫中,我可以檢索它嗎?如果沒有,那麼請告訴我。

問候

回答

2

在SQLite中存儲圖像不是一個好主意。您應該將圖像保存在SD卡上並將其路徑存儲在數據庫中。

無論如何,如果你仍然想存儲在數據庫中的圖像,那麼你需要做到以下幾點:

  1. 轉換圖像轉換成字節
  2. 轉換字節爲Base64編碼字符串
  3. 保存的Base64編碼的字符串到數據庫中

* 反轉過程會給出圖像。

另一種解決方案是將您的列smallThumb類型轉換爲BLOB並直接存儲字節。但爲此,你需要修改你的表格。如果你想存儲在數據庫中,你必須使用BLOB圖像

public String imageToDB (byte[] image){ 
    return Base64.encodeToString(image, Base64.DEFAULT).trim(); 
} 
+0

我怎樣才能找回它回來? – 2012-03-16 09:29:20

+0

簡單地通過從數據庫中獲取Base64字符串,然後'byte [] image = Base64.decode(「Base64StringfromDatabase」,Base64.DEFAULT);' – waqaslam 2012-03-16 09:32:43

+0

btw,它不讀什麼Base64 – 2012-03-16 09:32:49

0

我想你應該更好地存儲圖像路徑,而不是數據庫中的圖像數據。

當您檢索數據時,只需從路徑加載圖像。

1


在你的代碼,改變方法imageToDB如下。

SQL:

"CREATE TABLE TABLE_NAME (ID INTEGER PRIMARY KEY, ....., IMAGE_COLUMN BLOB)"; 


public void save(..., byte[] image ,...) { 
    ...... 
    ContentValues values = new ContentValues(); 
    values.put("ID", ...); 
    ..... 
    values.put("IMAGE_COLUMN", image); 
    ..... 
    db.insert(TABLE_NAME, null, values); 
} 
0

我認爲這是一個可怕的做法。

而且,這纔是真正的格式

mDb.execSQL(updateQuery, Object[] arg); 

public Object imageToDB (byte[] image){ 
    return (Object)image; 
} 

變化String valVar[] to Object valVar[]類型。它會在圖像存儲爲字節BLOB。

0

,如果你真的想用你的方法byte[] -> string to save to database,你需要做的遵循獲得:

String str = get from your database; 
    byte[] bytes = str.getBytes(); 
    Bitmap map = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);