Android - Bitmap.createScaledBitmap() 将 Config 设置为 ARGB_8888

5
这是我第一次遇到一个问题,尽管进行了彻底的搜索,但似乎还没有人问过。
我在使用Bitmap.createScaledBitmap()时遇到了问题,其结果缩放位图始终为ARGB_8888,而不考虑输入的配置。当然,在使用有限内存时,这是一个问题。
        InputStream is;
    try {
        is = mAssets.open("test.png");
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Config.ARGB_4444;
        Bitmap originalBitmap = BitmapFactory.decodeStream(is, null, opts);
        System.out.println("Original Config: " + originalBitmap.getConfig());
        mScale = (float) mHeight / originalBitmap.getHeight();
        mBitmapScaled = Bitmap.createScaledBitmap(originalBitmap, (int)(mScale*(float)originalBitmap.getWidth()),
                (int)(mScale*(float)originalBitmap.getHeight()), true);
        System.out.println("Scaled: " + mBitmapScaled.getConfig());
        originalBitmap.recycle();
        is.close();
    } catch (IOException e) {
        // Do something.
    }

以上代码返回以下输出:
原始位图: ARGB_4444 缩放后: ARGB_8888
由于Bitmap.createScaledBitmap()方法不接受Config参数,因此似乎没有办法防止这种情况发生。有什么想法吗?

如果原始位图包含 alpha 通道,则将返回 ARGB_8888。否则返回 RGB_565。如果不想使用 ARGB_8888,请勿使用 createScaledBitmap,而应该使用 Canvas - Alan
1个回答

6

createScaledBitmap(...) creates a new, scaled Bitmap and therefore passes in your supplied arguments to the createBitmap(...) method.

The following is a snippet from the source code of createBitmap(...):

    if (config != null) {
        switch (config) {
            case RGB_565:
                newConfig = Config.RGB_565;
                break;
            case ALPHA_8:
                newConfig = Config.ALPHA_8;
                break;
            //noinspection deprecation
            case ARGB_4444:
            case ARGB_8888:
            default:
                newConfig = Config.ARGB_8888;
                break;
        }
    }

Every Bitmap with the ARGB_4444 configuration gets converted to an ARGB_8888 Bitmap as you can see. So to answer your question: No, there is no way to prevent this (unless you want to copy parts of the Bitmap.java source code and create your own scaling method).

Why do Bitmaps with the ARGB_4444 configuration get converted to ARGB_8888?

The documentation states it like this:

ARGB_4444:

This field is deprecated. Because of the poor quality of this configuration, it is advised to use ARGB_8888 instead.


1
谢谢Ahmad,非常有用。我想给你点赞,但我还没有达到所需的声望值。我一定会回来的,等我有了声望值就会给你点赞。 - MaxAlexander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接