Skip to content Skip to sidebar Skip to footer

How To Reduce Image Size After Loading From Url In Android?

I'm getting image from the web when the image size is large i'm getting the following error java.lang.OutOfMemoryError: bitmap size exceeds VM budget My code is as follows i'm loa

Solution 1:

I did something like this:

privatestaticfinalfloatMAX_IMAGE_SIZE=800;
privatestaticfinalStringCURRENTLY_PROCESSED_IMAGE="currentlyProcessedImage.jpg";
InputStream stream;
StringfilePath=null;
try {
    //set stream and prepare image
    stream = getContentResolver().openInputStream(data.getData());
    UriimagePath= data.getData();
    BitmaprealImage= BitmapFactory.decodeStream(stream);

    //resize to 800x800 (proportionally)floatratio= Math.min( (float)MAX_IMAGE_SIZE / realImage.getWidth(), (float)MAX_IMAGE_SIZE / realImage.getHeight() );
    Log.i("PixMe", "Ratio: " + String.valueOf(ratio));
    intwidth= Math.round((float)ratio * realImage.getWidth());
    intheight= Math.round((float)ratio * realImage.getHeight());

    //scale down the imageBitmapnewBitmap= Bitmap.createScaledBitmap(realImage, width, height, true);

    //prepare cache dir
    filePath = getFilesDir().getAbsolutePath()
        + File.separator + CURRENTLY_PROCESSED_IMAGE;
    // String filePath = Environment.getExternalStorageDirectory()// + File.separator + bufferPath;ByteArrayOutputStreambytes=newByteArrayOutputStream();

    //save scaled down image to cache dir
    newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

    FileimageFile=newFile(filePath);

    // write the bytes in fileFileOutputStreamfo=newFileOutputStream(imageFile);
    fo.write(bytes.toByteArray());
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Solution 2:

You can implement like this:

   BitmapFactory.Optionso=newBitmapFactory.Options();
   o.inSampleSize = 2;
   Bitmapbit= BitmapFactory.decodeStream(inputStream,null,o);
   Bitmapscaled= Bitmap.createScaledBitmap(bit, width, height, true);
   bit.recycle();

Solution 3:

Are you using a lot of images? In that case make sure that you call recycle() on every Bitmap of every ImageView that is not visible anymore. That solved a lot of OOM-Exceptions for me.

Post a Comment for "How To Reduce Image Size After Loading From Url In Android?"