I trying to resize one image from InputStream, so I use the code in Strange out of memory issue while loading an image to a Bitmap object but I don't know why this code always return Drawable without image.
This one works well:
private Drawable decodeFile(InputStream f){
try {
InputStream in2 = new BufferedInputStream(f);
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=2;
return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
} catch (Exception e) {
return null;
}
}
This one does not work:
private Drawable decodeFile(InputStream f){
try {
InputStream in1 = new BufferedInputStream(f);
InputStream in2 = new BufferedInputStream(f);
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in1,null,o);
//The new size we want to scale to
final int IMAGE_MAX_SIZE=90;
//Find the correct scale value. It should be the power of 2.
int scale = 2;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE /
(double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inJustDecodeBounds = false;
o2.inSampleSize=scale;
return new BitmapDrawable(BitmapFactory.decodeStream(in2, null, o2));
} catch (Exception e) {
return null;
}
}
why one option affect the other? how its possible if I use two different InputStream and Options?
Actually you have two different BufferedInputStream
but they internally use the only one InputStream
object because BufferedInputStream
is only a wrapper for InputStream
.
So you can't just call two times BitmapFactory.decodeStream
method on the same stream, it will definitely fail because the second time it wouldn't start decoding from the beginning of the stream. You need to reset your stream if it is supported or reopen it.
this is my code that works well, I hope this will help
//Decode image size
BitmapFactory.Options optionsIn = new BitmapFactory.Options();
optionsIn.inJustDecodeBounds = true; // the trick is HERE, avoiding memory leaks
BitmapFactory.decodeFile(filePath, optionsIn);
BitmapFactory.Options optionsOut = new BitmapFactory.Options();
int requiredWidth = ECameraConfig.getEntryById(Preferences.I_CAMERA_IMAGE_RESOLUTION.get()).getyAxe();
float bitmapWidth = optionsIn.outWidth;
int scale = Math.round(bitmapWidth / requiredWidth);
optionsOut.inSampleSize = scale;
optionsOut.inPurgeable = true;//avoiding memory leaks
return BitmapFactory.decodeFile(filePath, optionsOut);
And I belive you dont need 2 InputStream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With