android - OOM возникает, когда я отправляю изображения на сервер через модификацию - PullRequest
1 голос
/ 03 мая 2020

Я отправляю изображения на сервер через Retrofit. Я выбираю изображения из галереи. Хотя я уменьшаю разрешение изображения, ошибка OOM все же возникает. Обычно это нормально, когда я отправляю 3 или 4 изображения, но когда я отправляю 7 или более изображений на сервер, происходит сбой приложения (особенно устройства ниже) Код, который я получил Битовая карта:

private Bitmap getBitmap(Uri uri) {

InputStream in = null;
try {
    final int IMAGE_MAX_SIZE = 1000000; // 1.0MP
    in = getActivity().getContentResolver().openInputStream(uri);

    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(in, null, o);
    in.close();

    int scale = 1;
    while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) >
            IMAGE_MAX_SIZE) {
        scale++;
    }


    Bitmap bitmap = null;
    in = getActivity().getContentResolver().openInputStream(uri);
    if (scale > 1) {
        scale--;
        // scale to max possible inSampleSize that still yields an image
        // larger than target
        o = new BitmapFactory.Options();
        o.inSampleSize = scale;
        bitmap = BitmapFactory.decodeStream(in, null, o);

        // resize to desired dimensions
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();


        double y = Math.sqrt(IMAGE_MAX_SIZE
                / (((double) width) / height));
        double x = (y / height) * width;

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) x,
                (int) y, true);

        bitmap.recycle();
        bitmap = scaledBitmap ;

        System.gc();
    } else {

        bitmap = BitmapFactory.decodeStream(in);

    }
    in.close();

    Log.d(TAG, "bitmap size - width: " + bitmap.getWidth() + ", height: " + bitmap.getHeight());

    return bitmap;

} catch (IOException e) {
    Log.e(TAG, e.getMessage(), e);
    return null;

}
}
...