Android Bitmap与byte[]、Bitmap与Drawable相互转化

柔情只为你懂 2022-06-13 04:47 334阅读 0赞

再很多时候我们需要Bitmap与byte[]、Bitmap与Drawable相互转化,我看网上大多数博客都是复制粘贴的,又乱又不好看,自己写了四个方法记录下来,直接拿过来就能用,方便自己也方便别人。
1、Bitmap与byte[]之间的转化

  1. public static byte[] getBytes(Bitmap bitmap){
  2. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  3. bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
  4. return baos.toByteArray();
  5. }
  6. public static Bitmap getBitmap(byte[] data){
  7. return BitmapFactory.decodeByteArray(data, 0, data.length);
  8. }

2、Bitmap与Drawable之间的转化

  1. public static Bitmap getBitmap(Context context, int drawable){
  2. Drawable mDrawable= ContextCompat.getDrawable(context, drawable);
  3. BitmapDrawable mBitmapDrawable=(BitmapDrawable)mDrawable;
  4. Bitmap mBitmap=mBitmapDrawable.getBitmap();
  5. return mBitmap;
  6. }
  7. public static Drawable getDrawable(Context context,Bitmap bitmap){
  8. Drawable mDrawable1=new BitmapDrawable(context.getResources(),bitmap);
  9. return mDrawable1;
  10. }

拿过来就能用,非常棒!

发表评论

表情:
评论列表 (有 0 条评论,334人围观)

还没有评论,来说两句吧...

相关阅读