天天看點

Bitmap 和 drawable 轉換

1.Drawable —>Bitmap

  • 自定義方法(需要自己轉換)
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(, , drawable.getIntrinsicWidth(), 
            drawable.draw(canvas);  
            return bitmap;

        }
           

上述方法中所用到的函數 參數詳解:

drawable.getOpacity()

直譯:得到不透明度
           

PixelFormat.OPAQUE

像素格式下的  不透明
           

drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565)

如果drawable 得到的不透明屬性 == 像素格式下的不透明度?
    Y:  格式為 ARGB_8888
    N:   格式為  RGB_565
           

bitmap.config

枚舉變量
public static final Bitmap.Config ALPHA_8
    public static final Bitmap.Config ARGB_4444
    public static final Bitmap.Config ARGB_8888
    public static final Bitmap.Config RGB_565
           

枚舉變量解釋

ALPHA_8 ARGB_4444 ARGB_8888 RGB_565

都是色彩的存儲方法:

A代表Alpha,
    R表示red,
    G表示green,
    B表示blue,

其實所有的可見色都是右紅綠藍組成的,是以紅綠藍又稱為三原色,每個原色都存儲着所表示顔色的資訊值
           
強力解釋
ALPHA_8  8位Alpha位圖
    就是Alpha由8位組成

ARGB_4444   16位ARGB位圖
    就是由4個4位組成即16位,

ARGB_8888   32位ARGB位圖
    就是由4個8位組成即32位,

RGB_565     16位8位RGB位圖
    就是R為5位,G為6位,B為5位共16位   
           

2.Bitmap ———–> Drawable

3.從資源中擷取Bitmap

  • 方法一
Resources res=getResources();  

        Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);  
           
  • 方法二

4.Bitmap ———–> byte[]

private byte[] Bitmap2Bytes(Bitmap bm){  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();    
        bm.compress(Bitmap.CompressFormat.PNG, , baos);    
        return baos.toByteArray();  
    }  
           

5.byte[] —————-> Bitmap

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

6.Bitmap ————–> int[]

int width = bmp.getWidth();
    int height = bmp.getHeight();
    int[] pixels = new int[width*height];   
    bmp.getPixels(pixels, , width, , , width, height);
    jni.StyleBaoColor(pixels, width, height);
    Bitmap bm2 = Bitmap.createBitmap(pixels, width, height, bmp.getConfig());