Bitmap 和 drawable 转换

来源:互联网 发布:线槽做弯的算法和图片 编辑:程序博客网 时间:2024/04/29 19:15

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(0, 0, 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

Drawable bd = new BitmapDrawable(Bitmap);

3.从资源中获取Bitmap

  • 方法一
Resources res=getResources();          Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic);  
  • 方法二
Drawable drawable = getResources().getDrawable(R.drawable.a);

4.Bitmap ———–> byte[]

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

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

private Bitmap Bytes2Bimap(byte[] b){              if(b.length!=0){                  return BitmapFactory.decodeByteArray(b, 0, 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, 0, width, 0, 0, width, height);    jni.StyleBaoColor(pixels, width, height);    Bitmap bm2 = Bitmap.createBitmap(pixels, width, height, bmp.getConfig());
0 0