打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Drawable、Bitmap、byte[]之间的转换问题

Drawable、Bitmap、byte[]之间的转换问题

分类: Android Development technology 97人阅读 评论(0) 收藏 举报

Android在处理一些图片资源的时候,会进行一些类型的转换,整理如下:


1、Drawable → Bitmap 的简单方法
((BitmapDrawable)res.getDrawable(R.drawable.youricon)).getBitmap();


2、Drawable → Bitmap

Java代码
public static Bitmap drawableToBitmap(Drawable drawable) {

Bitmap bitmap = Bitmap
.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
//canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}

Bitmap→Drawable 
BitmapDrawable bitmapDrawable = (BitmapDrawable)bitmap;
Drawable drawable = (Drawable)bitmapDrawable;
Bitmap bitmap = new Bitmap (...);
Drawable drawable = new BitmapDrawable(bitmap);


3、从资源中获取Bitmap
Java代码
Resources res=getResources();

Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);


4、Bitmap → byte[]
Java代码
private byte[] Bitmap2Bytes(Bitmap bm){
    ByteArrayOutputStream baos = newByteArrayOutputStream(); 
    bm.compress(Bitmap.CompressFormat.PNG, 100,baos); 
    return baos.toByteArray();
   }


5、 byte[] → Bitmap
Java代码
private Bitmap Bytes2Bimap(byte[] b){
if(b.length!=0){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
else {
return null;
}
}


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android Bitmap与DrawAble与byte[]与InputStream之间的转换工具类
Android中Bitmap和Drawable
实现Android图片圆角
Android Bitmap和Canvas笔记
android Bitmap学习总结
PTR Android Blog: Programmatically Coloring Drawables
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服