Android Drawable和Bitmap的转换实例详解
AndroidDrawable和Bitmap的转换实例详解
通常我们需要通过代码去设置图片,就需要设置图片Bitmap和Drawable的转换,下面整理了几种方式
一、Bitmap转Drawable
Bitmapbm=xxx;//xxx根据你的情况获取 BitmapDrawablebd=newBitmapDrawable(bm);//因为BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
二、Drawable转Bitmap
Drawabled=xxx;//xxx根据自己的情况获取drawable BitmapDrawablebd=(BitmapDrawable)d; Bitmapbm=bd.getBitmap(); //最终bm就是我们需要的Bitmap对象了。
从资源中获取Bitmap
publicstaticBitmapgetBitmapFromResources(Activityact,intresId){
Resourcesres=act.getResources();
returnBitmapFactory.decodeResource(res,resId);
}
byte[]→Bitmap
publicstaticBitmapconvertBytes2Bimap(byte[]b){
if(b.length==0){
returnnull;
}
returnBitmapFactory.decodeByteArray(b,0,b.length);
}
//Bitmap→byte[]
publicstaticbyte[]convertBitmap2Bytes(Bitmapbm){
ByteArrayOutputStreambaos=newByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG,100,baos);
returnbaos.toByteArray();
}
只是很简单代码片段,还是很容易懂得
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短