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释放相关的资源。

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();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值