2012-07-23 101 views
8

我試圖將一個圖像從字節[]轉換爲位圖,以在Android應用程序中顯示圖像。Android:如何將字節數組轉換爲位圖?

byte []的值由數據庫獲得,我檢查它不是null。 之後,我想轉換圖像,但不能成功。該程序顯示位圖的值爲空。

我覺得在轉換過程中有一些問題。

如果您知道任何提示,請告訴我。

byte[] image = null; 
Bitmap bitmap = null; 
     try { 
      if (rset4 != null) { 
       while (rset4.next()) { 
        image = rset4.getBytes("img"); 
        BitmapFactory.Options options = new BitmapFactory.Options(); 
        bitmap = BitmapFactory.decodeByteArray(image, 0, image.length, options); 
       } 
      } 
      if (bitmap != null) { 
       ImageView researcher_img = (ImageView) findViewById(R.id.researcher_img); 
       researcher_img.setImageBitmap(bitmap); 
       System.out.println("bitmap is not null"); 
      } else { 
       System.out.println("bitmap is null"); 
      } 

     } catch (SQLException e) { 

     } 

回答

6

從你的代碼,似乎你把字節數組的一部分,並在部分使用BitmapFactory.decodeByteArray方法。您需要在BitmapFactory.decodeByteArray方法中提供整個字節數組。

從評論

你需要改變你的選擇查詢(或至少知道有存儲在數據庫中的圖像的BLOB數據列的名稱(或指數))編輯。 getByte也使用ResultSet類的getBlob方法。假設列名稱是image_data。有了這個信息,更改您的代碼是這樣的:

byte[] image = null; 
Bitmap bitmap = null; 
    try { 
     if (rset4 != null) { 
       Blob blob = rset4.getBlob("image_data"); //This line gets the image's blob data 
       image = blob.getBytes(0, blob.length); //Convert blob to bytearray 
       BitmapFactory.Options options = new BitmapFactory.Options(); 
       bitmap = BitmapFactory.decodeByteArray(image, 0, image.length, options); //Convert bytearray to bitmap 
     //for performance free the memmory allocated by the bytearray and the blob variable 
     blob.free(); 
     image = null; 
     } 
     if (bitmap != null) { 
      ImageView researcher_img = (ImageView) findViewById(R.id.researcher_img); 
      researcher_img.setImageBitmap(bitmap); 
      System.out.println("bitmap is not null"); 
     } else { 
      System.out.println("bitmap is null"); 
     } 

    } catch (SQLException e) { 

    } 
+0

謝謝您的回覆!請讓我知道如何在該方法中提供整個字節數組。 – Benben 2012-07-23 14:17:47

+0

你能指定rset4'變量是什麼嗎?看到你的發佈代碼,這似乎有你的圖像的字節數組。 – Angelo 2012-07-23 14:20:09

+1

OK,rset4是ResultSet的值,用於存儲執行SQL的結果。 'ResultSet rset4 = null; rset4 = stmt4.executeQuery(「select * from images where id =」+ id);' – Benben 2012-07-23 14:26:23

12

使用下面一行的字節轉換成位圖,它是爲我工作。

Bitmap bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length); 

你需要把上面一行外環線的,因爲它需要字節數組轉換成位圖。

P.S. : - 這裏imageData是字節數組圖片

+0

非常感謝。但現在還不行。我也使用圖像的字節數組。 在我的字節數組中有一些問題...? – Benben 2012-07-23 14:19:41

相關問題