Reputation: 831
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 loading the image by using the LoadImageFromWebOperatins
method.
animation.addFrame(LoadImageFromWebOperations(feed.getItem(i).getImage()), 2500);
animation.addFrame(LoadImageFromWebOperations(feed.getItem(i).getImage1()), 2500); animation.setOneShot(false);
iv.setBackgroundDrawable(animation);
iv.post(new Starter());
private Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
In this case how do i solve this error? please provide solution for this.
Upvotes: 1
Views: 3334
Reputation: 1632
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.
Upvotes: 0
Reputation: 128448
You can implement like this:
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 2;
Bitmap bit = BitmapFactory.decodeStream(inputStream,null,o);
Bitmap scaled = Bitmap.createScaledBitmap(bit, width, height, true);
bit.recycle();
Upvotes: 2
Reputation: 21979
I did something like this:
private static final float MAX_IMAGE_SIZE = 800;
private static final String CURRENTLY_PROCESSED_IMAGE = "currentlyProcessedImage.jpg";
InputStream stream;
String filePath = null;
try {
//set stream and prepare image
stream = getContentResolver().openInputStream(data.getData());
Uri imagePath = data.getData();
Bitmap realImage = BitmapFactory.decodeStream(stream);
//resize to 800x800 (proportionally)
float ratio = Math.min( (float)MAX_IMAGE_SIZE / realImage.getWidth(), (float)MAX_IMAGE_SIZE / realImage.getHeight() );
Log.i("PixMe", "Ratio: " + String.valueOf(ratio));
int width = Math.round((float)ratio * realImage.getWidth());
int height = Math.round((float)ratio * realImage.getHeight());
//scale down the image
Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width, height, true);
//prepare cache dir
filePath = getFilesDir().getAbsolutePath()
+ File.separator + CURRENTLY_PROCESSED_IMAGE;
// String filePath = Environment.getExternalStorageDirectory()
// + File.separator + bufferPath;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//save scaled down image to cache dir
newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File imageFile = new File(filePath);
// write the bytes in file
FileOutputStream fo = new FileOutputStream(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();
}
Upvotes: 2