Drawable、Bitmap、byte[]之間的轉換

android在處理一寫圖片資源的時候,會進行一些類型的轉換,如今有空整理一下:android

 

一、Drawable → Bitmapcanvas

Java代碼  收藏代碼spa

  1. public static Bitmap drawableToBitmap(Drawable drawable) {  code

  2.           

  3.         Bitmap bitmap = Bitmap  orm

  4.                         .createBitmap(  圖片

  5.                                         drawable.getIntrinsicWidth(),  ci

  6.                                         drawable.getIntrinsicHeight(),  資源

  7.                                         drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  get

  8.                                                         : Bitmap.Config.RGB_565);  it

  9.         Canvas canvas = new Canvas(bitmap);  

  10.         //canvas.setBitmap(bitmap);  

  11.         drawable.setBounds(00, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  

  12.         drawable.draw(canvas);  

  13.         return bitmap;  

  14. }  

 

二、從資源中獲取Bitmap

 

Java代碼  收藏代碼

  1. Resources res=getResources();  

  2.   

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

 

三、Bitmap → byte[]

 

Java代碼  收藏代碼

  1. private byte[] Bitmap2Bytes(Bitmap bm){  

  2.     ByteArrayOutputStream baos = new ByteArrayOutputStream();    

  3.     bm.compress(Bitmap.CompressFormat.PNG, 100, baos);    

  4.     return baos.toByteArray();  

  5.    }  

 
四、 byte[] → Bitmap

Java代碼  收藏代碼

  1. private Bitmap Bytes2Bimap(byte[] b){  

  2.             if(b.length!=0){  

  3.                 return BitmapFactory.decodeByteArray(b, 0, b.length);  

  4.             }  

  5.             else {  

  6.                 return null;  

  7.             }  

  8.       }  

相關文章
相關標籤/搜索