Bitmap, Drawable, Byte之间的转化

来源:互联网 发布:汽车竞猜源码 编辑:程序博客网 时间:2024/06/13 17:23

1.  Bitmap 转化为 byte
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);  //bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream);

//AndroidSDK暂只支持PNG、JPG格式的压缩
byte[] array= out.toByteArray();

 

2. byte转化为bitmap
『byte[] data』

 

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

3. bitmap转化为Drawable
Drawable drawable = new FastBitmapDrawable(bitmap);

 

4. Drawable转化为bitmap
 a. BitmapDrawable, FastBitmapDrawable直接用getBitmap
 b. 其他类型的Drawable用Canvas画到一个bitmap上
      Canvas canvas = new Canvas(bitmap)
      drawable.draw(canvas);

 

 

另,从资源得到一个bitmap:

Resources res=getResources();

1.

InputStream is=res.openRawResource(R.drawable.testpic1);

BitmapDrawable drawableBmp=new BitmapDrawable(is);

Bitmap bmp=drawableBmp.getBitmap();

 

2.

BitmapDrawable drawableBmp=(BitmapDrawable)res.getDrawable(R.drawable.testpic1);

Bitmap bmp=drawableBmp.getBitmap();