在开发中经常需要将Bitmap和Drawable两中资源进行相互转换。转换的方法有很多种方式,下面将一一介绍。
1、Drawable转成Bitmap
// 方式一: Resources res=getResources(); Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.sample_0); // 方式二: 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); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; }
2、Bitmap转成Drawable
Drawable drawable =new BitmapDrawable(bmp);
3、从资源中获取Bitmap
Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);
4、Bitmap转成byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray();
5、byte[]转成Bitmap
public Bitmap Bytes2Bimap(byte[] b){ if(b.length!=0){ return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } }