通过改造将图像发送到服务器时出现android-OOM

时间:2020-05-03 14:16:13

标签: android bitmap out-of-memory retrofit2

我通过翻新将图像发送到服务器。我从画廊挑选图像。尽管我降低了图像的分辨率,但仍然发生OOM错误。通常,当我发送3或4张图像时很好,但是当我向服务器发送7张或更多图像时,App崩溃了。(尤其是低端设备)我得到位图的代码:

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;

}
}

0 个答案:

没有答案