Android系统中Drawable Bitmap 和byte[] 直接的转换.
在BitmapFactory中有多种decodeBitmap的方法,可以从文件、资源、二进制流、输入流等多种方法获取Bitmap。详细情况可以参考BitmapFactory的java doc。
/**
* Convert Drawable to Bitmap
* @param drawable
* @return
*/
public Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() == PixelFormat.OPAQUE ?
Bitmap.Config.RGB_565: Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
/**
* Bitmap to byte array.
* @param bitmap
* @return
*/
public byte[] bitmapToBytes(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG/*OR JPEG*/, 100, baos);
return baos.toByteArray();
}
/**
* Use BitmapFactory decodeXXX method
* there are a lot of decode method . see the java doc
* @return
*/
public Bitmap getBitmap() {
return BitmapFactory.decodeFile("pic file path");
}