我需要具有從數據庫下載的圖像的圖像按鈕,即在構建時不可用。我見過的所有imagebutton示例都描述了將圖像放在「drawable」文件夾中,大概是在構建時。是否有可能在運行時加載製作/發現的圖像?Android圖像按鈕可以使用從數據庫檢索的圖像嗎?
1
A
回答
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) {}
}
}
}
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
相關問題
- 1. 從android數據庫的mysql數據庫檢索圖像
- 2. 從mvc.net的數據庫檢索圖像
- 3. 如何從數據庫使用數據庫檢索圖像?
- 4. 從數據庫中檢索圖像
- 5. 如何從數據庫檢索圖像?
- 6. 從sql數據庫檢索圖像
- 7. PHP從數據庫檢索新圖像
- 8. 從SQL Server數據庫檢索圖像
- 9. 從Oracle數據庫檢索圖像
- 10. 從訪問數據庫檢索圖像
- 11. 從數據庫檢索圖像ASP.NET MVC
- 12. 從數據庫插入/檢索圖像
- 13. Android - 從數據庫服務器檢索圖像和數據
- 14. 顯示從數據庫檢索圖像到圖像控制
- 15. 從數據庫檢索圖像到圖像標記
- 16. 我可以使用SVG圖像作爲按鈕圖標嗎?
- 17. 使用mvvm光從數據庫交換按鈕上的圖像
- 18. 使用PHP顯示從數據庫檢索的圖像
- 19. 使用c檢索從數據庫到asp.net頁面的圖像#
- 20. Android圖像按鈕
- 21. Android圖像按鈕
- 22. android圖像按鈕
- 23. 如何使用spring從Mysql數據庫中檢索圖像?
- 24. 使用PHP從postgres數據庫檢索圖像
- 25. 使用java從MYSQL數據庫檢索多個圖像
- 26. 使用Ajax從數據庫檢索圖像
- 27. 使用NHibernate從數據庫中檢索圖像字段UniqueResult()
- 28. 從sql server 2008數據庫檢索圖像使用c#
- 29. 使用cideigniter從數據庫檢索視頻和背景圖像
- 30. 如何使用C#從SQL數據庫檢索圖像?
然後用imageView代替imageButton? – Bandjalong 2013-04-26 01:11:13
使用「位圖」而不是「BitmapDrawable」。我編輯了我的答案以反映這一點。 – 2013-04-26 01:20:37
有道理 - 謝謝! – Bandjalong 2013-04-26 01:33:24