Android中Bitmap、Drawable、byte[]互转

Bitmap -> Drawable

1
Drawable drawable = new BitmapDrawable(bmp);

Drawable -> Bitmap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Drawable资源
Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.sample);

//Drawable对象
public Bitmap drawable2Bitmap(Drawable drawable) {
Config config;
if (drawable.getOpacity() != PixelFormat.OPAQUE) {
config = Bitmap.Config.ARGB_8888;
} else {
config = Bitmap.Config.RGB_565;
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), config);
Canvas canvas = new Canvas(bitmap);
// canvas.setBitmap(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}

Bitmap -> byte[]

1
2
3
4
5
private byte[] bitmap2Bytes(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}

byte[] -> Bitmap

1
2
3
4
5
6
7
private Bitmap bytes2Bitmap(byte[] bytes) {
if (bytes.length != 0) {
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
} else {
return null;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :