2013-04-26 39 views

回答

1

是的,你可以。您需要從字節數組(可以從文件或數據庫中讀取)創建位圖。然後將字節數組轉換爲Bitmap。例如:

Bitmap bitmap = bytesToBitmap(<your byte array here>); 
ImageButton button = (ImageButton)findViewById(R.id.my_button); 
button.setImageBitmap(bitmap); 

public static Bitmap bytesToBitmap(byte[] bytes) 
{ 
    ByteArrayInputStream imageStream = null; 

    try 
    { 
     imageStream = new ByteArrayInputStream(bytes); 
     return BitmapFactory.decodeStream(imageStream); 
    } 
    catch (Exception ex) 
    { 
     Log.d("My Activity", "Unable to generate a bitmap: " + ex.getMessage()); 
     return null; 
    } 
    finally 
    { 
     if (imageStream != null) 
     { 
      try 
      { 
       imageStream.close(); 
      } 
      catch (Exception ex) {} 
     } 
    } 
} 
+0

然後用imageView代替imageButton? – Bandjalong 2013-04-26 01:11:13

+0

使用「位圖」而不是「BitmapDrawable」。我編輯了我的答案以反映這一點。 – 2013-04-26 01:20:37

+0

有道理 - 謝謝! – Bandjalong 2013-04-26 01:33:24

1

使用BLOB在數據庫中插入圖像。您先將字節[]轉換爲該圖像。

private static final String SQL_GETCONTENTS = 
     "CREATE TABLE " + DB_TABLE + "("+ 
       KEY_CONTENTSID + " TEXT," + 
       KEY_IMAGE + " BLOB);"; 

public void addEntry(String id, byte[] image) throws SQLiteException{ 
    ContentValues cv = new ContentValues(); 
    cv.put(KEY_CONTENTSID, id); 
    cv.put(KEY_IMAGE, image); 
    database.insert(DB_TABLE, null, cv); 
} 


public Cursor getEntry(String id){ 
    String sql = "select * from " + DB_TABLE + " where " + KEY_CONTENTSID + "='" + id + "'"; 
    Cursor c = database.rawQuery(sql, null); 
    c.moveToFirst(); 
    return c; 
} 

檢索圖像,並設置:

Cursor c = entry.getEntry(idKey); 
byte[] image = c.getBlob(0); 
BitmapFactory.Options bfOptions=new BitmapFactory.Options(); 
bfOptions.inDither = false; 
bfOptions.inPurgeable = true; 
bfOptions.inInputShareable = true; 

thumbImage.setImageBitmap(BitmapFactory.decodeByteArray(image, 0, image.length, bfOptions)); 

使用BitmapFactory.Options將有助於避免一些OutOfMemory異常。

+0

非常方便,謝謝! – Bandjalong 2013-04-26 01:32:37