Drawable、Bitmap、ByteArray学习

Drawable:Android下的图形对象,可以装载png、gif、jpg、bmp等格式图像。

Bitmap:位图,文件格式一般为bmp。可以将png、jpg、gif等格式图像转换成Bitmap。

ByteArray:存放着图像的像素数据。

  占用内存 绘制速度 支持像素操作 支持旋转缩放 支持透明度
Bitmap 支持 支持 支持
Drawable 不支持 支持 支持

Bitmap获取主要方法:

        BitmapFactory.decode系列方法

        Bitmap.create系列方法

        因为Bitmap体积比较大,在使用的时候需要注意回收不再使用的Bitmap,以早点促使GC释放相关的资源。

扫描二维码关注公众号,回复: 8883094 查看本文章
if(bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }

Drawable获取主要方法:

        getResource().getDrawable(R.drawable.icon)

注意:

1、Drawable是一个抽象类

2、Drawable有一个常用的子类BitmapDrawable,可以和Bitmap相互转换

3、Drawable的内存占用和绘制效率优于Bitmap,但是Drawable不可以操作像素,Bitmap可以操作像素

Bitmap转化成Drawable:

Drawable drawable = new BitmapDrawable(getResources(), bitmap);

Drawable转化成Bitmap:

Bitmap bitmap = bitmapDrawable.getBitmap();
public Bitmap getBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
        Bitmap bitmap = Bitmap.createBitmap(width, height, config);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;
    }

ByteArray转化成Bitmap

public void getBitmap(byte[] byteArray) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    }

Bitmap转换成ByteArray

public byte[] getByteArray(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        return out.toByteArray();
    }
    public void getByteArray(Bitmap bitmap) {
        int size = bitmap.getAllocationByteCount();
        ByteBuffer buffer = ByteBuffer.allocate(size);
        bitmap.copyPixelsToBuffer(buffer);
        byte[] byteArray = buffer.array();
    }
发布了81 篇原创文章 · 获赞 4 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/GracefulGuigui/article/details/104050592