作者:手机用户2502905845 | 来源:互联网 | 2023-05-19 06:04
以下是在开发中常用的对Drawable和Bitmap的获取、转换等操作,非常基础,仅供需要时使用Bitmap转DrawablepublicDrawableconvertBitmap2Drawa
以下是在开发中常用的对Drawable和Bitmap的获取、转换等操作,非常基础,仅供需要时使用
//Bitmap转Drawable
public Drawable convertBitmap2Drawable(Bitmap bitmap) {
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
return bitmapDrawable;
}
// Drawable转Bitmap
public Bitmap convertDrawable2Bitmap(Drawable drawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
return bitmap;
}
//通过Canvas把Drawable转化为Bitmap(可以在转化的过程中对图片进行处理)
public static Bitmap convertDrawable2BitmapByCanvas(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.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
//从资源文件中获取Bitmap
public static Bitmap getBitmapFromResources(Context context, int resId) {
Resources res = context.getResources();
return BitmapFactory.decodeResource(res, resId);
}
//byte数组转化为Bitmap
public static Bitmap convertBytes2Bimap(byte[] b) {
if (b.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
//Bitmap转化为byte数组
public static byte[] convertBitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}