我需要带有从数据库下载的图像的图像按钮,即在构建时不可用。我见过的所有图像按钮示例都描述了将图像放在“可绘制”文件夹中,大概是在构建时。是否可以加载在运行时创建/找到的图像?
答案 0 :(得分: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 :(得分:1)
使用BLOB在DB中插入图像。您已先在byte []中转换该图像。
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
将有助于避免一些外部存储异常。