設置了 Bitmap.Config.RGB_565 無效

項目裏面看到一張圖片佔用內存很大,想優化一下

首先是用了glide,但是發現設置了format 跟不設置是一樣的,非常不理解

後面又想用android 原生的API 來解析圖片,以爲這樣就可以生效了

 BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.RGB_565;
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap, options);
            Log.i("bitmap", "name: " + bitmap.getConfig().name());

但通過內存分析發現無論我設置成什麼佔用內存大小都是一樣的!!後面打印了bitmap 的config 才發現原來沒改成功!

使用Glide 也是一樣的效果

   private void loadBitmap(int width, int height, ImageView imageView, int resId) {
        Glide.with(this).load(resId).
                asBitmap().format(DecodeFormat.PREFER_RGB_565).
                override(dp2px(this, width), dp2px(this, height)).
                into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        Log.i("bitmap", "onResourceReady: " + resource.getConfig().name());
                    }
                });
    }

打印結果還是顯示的是

網上的解決方案:

一、

private Bitmap convert(Bitmap bitmap, Bitmap.Config config) {
    Bitmap convertedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), config);
    Canvas canvas = new Canvas(convertedBitmap);
    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    canvas.drawBitmap(bitmap, 0, 0, paint);
    return convertedBitmap;
}

二、 

Bitmap converted = original.copy(Config.RGB_565, false);

偶爾幾張圖片不能轉換還好,但如果很多圖片都不支持就很尷尬了,難道要放棄使用glide?目前還沒找到哪些圖片不支持轉換的資料!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章