Почему я продолжаю получать исключения при повторном использовании растровых изображений?

фон

начиная с API 11, вы можете повторно использовать растровые изображения при декодировании новых, чтобы декодер не нуждался в повторном создании совершенно новых больших объектов.

это делается с помощью чего-то вроде этого кода (взятого из этот учебник):

mCurrentBitmap = Bitmap.createBitmap(imageWidth,imageHeight,Bitmap.Config.ARGB_8888);
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inBitmap = mCurrentBitmap;
bitmapOptions.inSampleSize = 1;
mCurrentBitmap = BitmapFactory.decodeResource(getResources(),imageResId, bitmapOptions);

преимущество совершенно очевидно: использование в некоторых случаях меньшего количества памяти, оказывающее меньшее давление на GC и имеющее лучшую производительность, потому что вам не нужно создавать гораздо более крупные объекты.

Единственный улов в том, что оба изображения должны иметь одинаковый размер и конфигурацию.

проблема

хотя код отлично работает с ресурсами самого проекта (в папке res), я всегда получаю следующую ошибку при обработке файлов изображений, которые я разместил во внутреннем хранилище:

java.lang.IllegalArgumentException: Problem decoding into existing bitmap

Я попробовал несколько разных флагов для параметров растрового изображения:

bitmapOptions.inPurgeable = true;
bitmapOptions.inInputShareable = true;
bitmapOptions.inMutable = true;
bitmapOptions.inScaled = false;
bitmapOptions.inSampleSize = 1;
bitmapOptions.inPreferredConfig = Config.RGB_565; //i've set the created bitmap to be of this type too, of course

Я также пробовал как decodeFile, так и decodeStream для BitmapFactory.

здесь пример кода, чтобы показать, что есть проблема (основанная на примере, о котором я писал):

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bitmap_allocation);

    final int[] imageIDs = { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e, R.drawable.f };

    final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
    final TextView durationTextview = (TextView) findViewById(R.id.loadDuration);
    final ImageView imageview = (ImageView) findViewById(R.id.imageview);

    // Create bitmap to be re-used, based on the size of one of the bitmaps
    mBitmapOptions = new BitmapFactory.Options();
    mBitmapOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(getResources(), R.drawable.a, mBitmapOptions);
    mCurrentBitmap = Bitmap.createBitmap(mBitmapOptions.outWidth, mBitmapOptions.outHeight, Bitmap.Config.ARGB_8888);
    mBitmapOptions.inJustDecodeBounds = false;
    mBitmapOptions.inBitmap = mCurrentBitmap;
    mBitmapOptions.inSampleSize = 1;
    mBitmapOptions.inPreferredConfig = Config.ARGB_8888;
    BitmapFactory.decodeResource(getResources(), R.drawable.a, mBitmapOptions);
    imageview.setImageBitmap(mCurrentBitmap);

    // When the user clicks on the image, load the next one in the list
    imageview.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(final View v) {
            mCurrentIndex = (mCurrentIndex + 1) % imageIDs.length;
            Options bitmapOptions = new Options();
            bitmapOptions.inPreferredConfig = Config.ARGB_8888;
            if (checkbox.isChecked()) {
                // Re-use the bitmap by using BitmapOptions.inBitmap
                bitmapOptions = mBitmapOptions;
                bitmapOptions.inBitmap = mCurrentBitmap;
            }
            final long startTime = System.currentTimeMillis();
            //
            File tempFile = null;
            try {
                tempFile = File.createTempFile("temp", ".webp", getApplicationContext().getCacheDir());
                FileOutputStream fileOutputStream;
                final Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageIDs[mCurrentIndex]);
                bitmap.compress(CompressFormat.WEBP, 100, fileOutputStream = new FileOutputStream(tempFile));
                fileOutputStream.flush();
                fileOutputStream.close();
            final InputStream inputStream = new FileInputStream(tempFile);
            mCurrentBitmap = BitmapFactory.decodeStream(inputStream,null,bitmapOptions);
            inputStream.close();
            } catch (final IOException e1) {
                e1.printStackTrace();
            }
            imageview.setImageBitmap(mCurrentBitmap);

            // One way you can see the difference between reusing and not is through the
            // timing reported here. But you can also see a huge impact in the garbage
            // collector if you look at logcat with and without reuse. Avoiding garbage
            // collection when possible, especially for large items like bitmaps,
            // is always a good idea.
            durationTextview.setText("Load took " + (System.currentTimeMillis() - startTime));
        }
    });
}

вопрос

почему я продолжаю получать эту ошибку и как ее исправить?

Я нашел несколько похожих вопросов, но никто не ответил.

Ответ 1

Кажется, что проблема с этим прохладным советом при использовании файлов webP.

Мне просто нужно использовать либо jpg, либо png.