Android内存中的大胖小子_Bitmap

2020-03-04  本文已影响0人  dashingqi

Bitmap的内存模型

Android的Bitmap内存管理也是随着版本的迭代在不断的演进

API10之前
API10 到 API26
API26之后

Bitmap的像素格式(也就是一个像素占用的内存大小)

ARGB_8888(Android默认使用的像素格式)
ARGB_4444
RGB_565
ALPHA_8

Bitmap占有的内存

getByteCount()

getAllocationByteCount()

Bitmap的内存回收

Bitmap的内存复用

怎么复用
复用也是有版本的问题的

说下getByteCount()和getAllocationByteCount()的区别

计算Bitmap占用的内存

让人想到的就是: width x height x 一个像素占用的内存大小

BitmapFactory.decodeResource()

BitmapFactory.decodeFile()

Bitmap的压缩

质量压缩(Bitmap.compress())

/**
     * 质量压缩
     * @param bitmap
     * @return
     */
    private Bitmap compressBitmap(Bitmap bitmap) {
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ous);
        int options = 100;
        while (ous.toByteArray().length / 1024 > 100) {
            ous.reset();
            options -= 10;
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, ous);
            
        }
        ByteArrayInputStream bIn = new ByteArrayInputStream(ous.toByteArray());
        Bitmap compressBitmap = BitmapFactory.decodeStream(bIn, null, null);
        return compressBitmap;
    }
质量压缩后的Bitmap,再次保存到本地变大了?
public static boolean saveBitmapToJPG(Bitmap bitmap, File file) {
    if (bitmap == null)
        return false;
    FileOutputStream fos = null;
     if (file.exists()){
         file.delete();
     }
    try {
        fos = new FileOutputStream(file);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}


可以这样搞
 compressPic(BitmapFactory.decodeResource(getResources(),R.drawable.scal_density));
        String path = Environment.getExternalStorageDirectory().getPath();
        File file = new File(path, "/test/2.jpg");
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(ous.toByteArray());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

采样率压缩(BitmapFactory.Options.inSampleSize)

Bitmap知识点.png
上一篇 下一篇

猜你喜欢

热点阅读