I'm trying to download imags from a url and then decode them. The problem is that I don't know how large are they and if I decode them right away, the app crashes with too-big images.
I'm doing the following and it works with most of the images but with some of them, it throws the java.io.IOException: Mark has been invalidated
exception.
It's not a matter of size because it happens with a 75KB or a 120KB image and not with a 20MB or 45KB image.
Also the format is not important as it can happen either with a jpg or png image.
pis
is an InputStream
.
Options opts = new BitmapFactory.Options();
BufferedInputStream bis = new BufferedInputStream(pis);
bis.mark(1024 * 1024);
opts.inJustDecodeBounds = true;
Bitmap bmImg=BitmapFactory.decodeStream(bis,null,opts);
Log.e("optwidth",opts.outWidth+"");
try {
bis.reset();
opts.inJustDecodeBounds = false;
int ratio = opts.outWidth/800;
Log.e("ratio",String.valueOf(ratio));
if (opts.outWidth>=800)opts.inSampleSize = ratio;
return BitmapFactory.decodeStream(bis,null,opts);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}