Android 中 资源文件图片转 Bitmap 和 Drawable 以及相互转换的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35619188/article/details/84871270

Android 图片转换的方法总结:
一、Bitmap 转换成 Drawable
对 Bitmap 进行强制转换

Drawable drawable = new BitmapDrawable(bmp);

二、Drawable 转换成 Bitmap
方法一
通过 BitmapFactory 中的 decodeResource 方法,将资源文件中的R.mipmap.ic_launcher 转化成Bitmap。

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

方法二
根据Drawable创建一个新的Bitmap,封装一个方法:

public static Bitmap drawableToBitmap(Drawable drawable) {
        int w = drawable.getIntrinsicWidth();//获取宽
        int h = drawable.getIntrinsicHeight();//获取高
        Bitmap.Config btmConfig =drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888: Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(w, h, btmConfig);
        //绘制新的bitmap
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        //返回bitmap
        return bitmap;
    }

方法三
将 Drable 对象转化成 BitmapDrawable ,然后调用 getBitmap 方法获取

 Drawable drawable =getResources().getDrawable(R.mipmap.ic_launcher);//获取drawable
 BitmapDrawable bd = (BitmapDrawable) drawable;
 Bitmap bm= bd.getBitmap();

三、Bitmap 转换成 byte[]
封装方法

    //Bitmap 转换成 byte[]
    public static byte[] bitmapToBytes(Bitmap bitmap){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

四、byte[] 转化成 Bitmap
封装方法

    public static Bitmap bytesToBitmap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length); //返回bitmap
        } else {
            return null;
        }
    }

参考链接

猜你喜欢

转载自blog.csdn.net/qq_35619188/article/details/84871270