Android之Drawable转换drawable、bitmap、byte[]

在代码中我们有时需要获取res下的资源文件,

尤其是Drawable的图片文件并转换bitmap,或者相互转换


Drawable  转  Bitmap

方法一:

Drawable drawable = getResources().getDrawable(R.drawable.icon);
imageview.setBackground(drawable);


方法二:

Inputstream is = getResources().openRawResource(R.drawable.icon);
BitmapDrawable mapDraw = new BitmapDrawable(is);
Bitmap bitmap = mapDraw.getBitmap();

InputStream is = getResources().openRawResource(R.drawable.icon);  
Bitmap bitmap = BitmapFactory.decodeStream(is);


方法三:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Bitmap iconBitmap = bitmap.createBitmap( 300, 300, Config.ARGB_8888 );


方法四:

public 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;
}


Bitmap  转  Drawable

Drawable drawable =new BitmapDrawable(bitmap);


Bitmap  转  byte[ ]

public static byte[] getBytes(Bitmap bitmap){
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
     return baos.toByteArray();   
}

byte[] 转 Bitmap

public static Bitmap Bytes2Bimap(byte[] b) {
     if (b.length != 0) {
          return BitmapFactory.decodeByteArray(b, 0, b.length);
     } else {
          return null;
     }
}

...








你可能感兴趣的:(Android常见基础)