Decrease the quality of image . OutOfMemory Exception - Android - java

I am trying to implement the application which is doing lots of operations on an image. I have the problem with optimalization. The time of running my application is too long. I need to compress the images that I'm processing. I was trying with this tutorial:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
It works well when I want to take the image from drawable folder. The problem is when I want to take the picture from camera or gallery. I have no idea what should I put in " R.id.myimage"
So the question is, how to use this line of code:
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
when I want to use the camera or gallery instead of drawable folder ?

To avoid OOM error, scale image using:
//For resource
image.setImageBitmap(decodeSampledBitmapFromResource("android.resource://com.my.package/drawable/image_name"));
//For file
image.setImageBitmap(decodeSampledBitmapFromResource(filepath));
Sampling function:
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 2;
if (height >= reqHeight || width >= reqWidth) {
inSampleSize *= 2;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String file,
int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}

Related

load bitmap from url the right way

ok guys need a little help, so I’ve got an app that creates a bitmap images from memory and displays it as an image view, i got to this stage by following the android developer guidelines so it has image scaling, cashing and so on, but now i want to replace the image in memory with one from a website, here is my current code
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight){
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
and this is some code i found to make an image from url
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}catch(IOException e){
e.printStackTrace();
return null;
}
}
i want to know how to implement this to my existing code to incorporate scaling the image to the right resolution to fit my imageView before loading it into memory with the inJustDecodeBounds set to true inorder to avoid outOfMemory exception or is there no longer any need to do this
If you want to do it online i would recommend you using volley imageLoader, the code you are using is downloading. I would recommend you do some research before going into this though, it is a tad bit different that what you would usually do, but once you get it image loading only requires a few lines.On another note if you still wish to download it, change it into bitmap and read it straight from the file.Furthermore to display image from storage doesn't require that much work, an example is at the bottom.
http://blog.lemberg.co.uk/volley-part-3-image-loader
private void loadImageFromStorage(String path, String Name) {
try {
File f = new File(path, Name+".jpg");
double bytes = f.length();
Bitmap b;
if(bytes < 1){
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
}
else{
b = BitmapFactory.decodeStream(new FileInputStream(f));
}
imageView = (ImageView).findViewById(R.id.grid_image);
imageView.setImageBitmap(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Bitmap resizing causes out of memory

I have a simple class for resizing bitmap images according to my requirement. There is a simple method responsible for it as follows:
public static Bitmap ResizeRichImages(Bitmap bitmap, Context mContext){
try {
float originalBitmapWidth = bitmap.getWidth();
float originalBitmapHeight = bitmap.getHeight();
float originalAspectRatio = originalBitmapWidth/originalBitmapHeight;
double width_percentage = (0.05*screenWidthPixels(mContext));
float newWidth = (float)((int)screenWidthPixels(mContext)-width_percentage);
float newBitmapWidth = newWidth;
float newBitmapHeight = newBitmapWidth/originalAspectRatio;
bitmap = Bitmap.createScaledBitmap(bitmap, (int) newWidth, (int)newBitmapHeight, false);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
And this is how I call this method:
String URL = "https://maps.googleapis.com/maps/api/staticmap?center=-33.86527274921529,151.2050531328867&zoom=15&size=640x360&sensor=false&markers=color:blue%7Clabel:!%7C-33.86527274921529,151.2050531328867";
try {
bmp = Picasso.with(ViewStory.this).load(URL)
.get();
bmp = ImageController.ResizeRichImages(bmp, ViewStory.this);
} catch (Exception e) {
e.printStackTrace();
}
But, almost every time I am getting the out of memory exception while calling the ResizeRichImages method. Where am I going wrong?
Instead using largeHeap option in manifest which should be always last option, you can try compressing like below code snippet.
*
byteArrImage = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if(data != null) thumbnail = (Bitmap) data.getExtras().get("data");
if(thumbnail != null) {
//thumbnail.compress(Bitmap.CompressFormat.PNG, 85, baos);
thumbnail.compress(Bitmap.CompressFormat.JPEG, 85, baos);
byteArrImage = baos.toByteArray();
uploadImageToServer();
}
I got same error before, but After some searching i found another way to resize large Bitmap image. When you use Bitmap with large image you have to scale image with BitmapFactory.Options.inSampleSize . The sample size is the number of pixels in either dimension that correspond to a single pixel in the decoded bitmap. When you use inSampleSize = 4 it returns an image that is 1/4 the width/height of the original.You can also see the more detail in android developer site.
Use this Method for resizing
private Bitmap decodeFileWithSmallSize(String sdcard_path) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap myBitmap = BitmapFactory.decodeFile(sdcard_path, options);
return myBitmap;
}
Use in Activity
try {
Bitmap bitmap = null;
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
bitmap = decodeFileWithSmallSize("path");
}
catch (OutOfMemoryError e)
{
Log.e("TAG",
"OutOfMemoryError Exception" + e.getMessage());
}
Generally while deal with bitmap we need to reduce the memory size by reducing the samplesize of bitmap based on our required width and height.
This functions takes bitmap file path if you want to pass bitmap change it with your requirement.But this the proper way to load images efficently.
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
This function calculates the sample size of required image in order to reduct he memory..
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
For more info refer this link:http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
In your case if you are targeting min level as 19 then go with reconfigure function which is available on api level 19
visit developers site
You haven't told us how big your bitmap is. Perhaps it's simply using up all of your free memory, especially if you have other large bitmaps (or something else) taking up much of it.
I would try running the procedure on a small bitmap, and with newBitmapWidth and newBitmapHeight reduced to a tenth of what they are now. If this eliminates the exception, it's pretty sure you need to optimize your memory use before you can handle the full size.

How to reduce image without losing quality and preserving the aspect ratio? [duplicate]

This question already has answers here:
Strange OutOfMemory issue while loading an image to a Bitmap object
(44 answers)
Closed 7 years ago.
I have image 3264х2448.
I load it in bitmap crudeImage = BitmapFactory.decodeFile(picturePath); then set to the ImageView imageCrop.setImageBitmap(crudeImage);
the problem is that it very big(3264х2448) and my library cropper
work very slowly with this image.
I want reduce the image to a smaller size. but to preserve the quality and proportion. how can this be done?
You should read Loading Large Bitmaps Efficiently.
Essentially, calculate the sample size first by
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
then load the image using the sample size:
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
I use this to resize my bitmap's. Maybe can be useful for you.
public Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight)
{
//bitmap it's the bitmap you want to resize
//newWidth and newHeight are the with and height that you want to the new bitmap
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) /height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
I hope this help you.
If you read the tutorial here you'll see google gives you a very comprehensive guide on how to scale bitmaps without excessive memory usage.
In particular, these two methods (from the tutorial):
public static Bitmap decodeSampledBitmapFromResource(File file, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(file, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Will accomplish your scaling whilst preserving aspect ratio.
The trick with these two methods is that the first decode operation is set to only decode the image's properties (dimensions and other information) as set by:
options.inJustDecodeBounds = true;
in which the new scale factor is calculated proportionally by the method calculateInSampleSize().
Then the image is decoded again, this time with
options.inJustDecodeBounds = false;
as well as the scale factor set, so the bitmap factory automatically scales whilst decoding, reducing the memory footprint.
Regarding what resolution the image needs to be decoded to, that really depends on your use-case. But, if the particular image does not need to be zoomed in later, you need no more than the device's physical screen size, which can be obtained via:
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getRealSize(size);
in which object size will hold the device's screen size.

How to set image as wallpaper without causing OutOfMemory error

I have a straight-forward wallpaper app which I've just finished coding. I've used the tutorial here ( http://developer.android.com/training/displaying-bitmaps/load-bitmap.html ) to load the image on the screen at a lower resolution, while I use the code below to set the wallpaper. imageId represents the currently selected drawable.
InputStream is = getResources().openRawResource(imageId);
Bitmap bitmap = BitmapFactory.decodeStream(is);
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(bitmap);
Toast.makeText(MainActivity.this, "Teamwork! Wallpaper set.",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(
MainActivity.this,
"Damnit, clickers! Wallpaper wasn't set. Try killing and restarting the app?",
Toast.LENGTH_LONG).show();
}
However, I fear that the above code may cause phones of less memory to crash when it is called. Is there anything I can do to prevent this from happening, or is there nothing to fear?
EDIT:
I used this code to display the images in the app:
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public void setImage() {
switch (imageNum) {
case 1:
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.aaaae,
options);
display.setImageBitmap(decodeSampledBitmapFromResource(
getResources(), R.drawable.aaaae, 300, 300));
imageId = R.drawable.aaaae;
break;
// Etc, etc.
}
}
The method setImage is called every time the "Next" button is pressed.
I guess you are not handling images properly
Here is the solution to handle bitmaps in android
(This approach can handle 25000px by 25000px images in a non-ui thread.)
First, you should calculate the sampleBitmapSize of the bitmap ( to load the lower version of the same bitmap )
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
Below is the util function to calculate InSampleSize ( an integer that defines the value (rating) of quality of a bitmap).
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
Log.i("ImageUtil", "InSampleSize: "+inSampleSize);
return inSampleSize;
}

Bitmap create out of memory

I am trying rotate taken image in onActivityResult() from camera Intent, but I am getting Out of memory errors occasionally.
How can I optimize this code?
http://pastebin.com/ieaHS8qB
bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
correctBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), mat, true);
I was trying to add bmp.recycle() and correctBmp.recycle() after these lines, but it didn't help.
if you develope your application api level 10+ you can add your manifest this
android:largeHeap="true" //add this entity.
like
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen" >
or try this (Create Class)
public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
thanks to that code you can also resize your bitmap.
try to add below code before decodestream and pass option as a parameter.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
options.inPurgeable = true;
options.inInputShareable = true;
bmp = BitmapFactory.decodeStream(new FileInputStream(f),null, options);

Categories