How can I resolve OutofMemoryError error? (After Bitmap.createScaledBitmap) - android

I know, there are a lot of similar questions in Stackoverflow. But I could not solve my problem.
I have some kind of jigsaw puzzle. The pictures in the Drawable-nodpi folder are 2500x1250.
I am trying to resize the images with the following code suggested:
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 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;
while ((halfHeight / inSampleSize) >= reqHeight
&& (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
I call it like this:
(I call these codes several times.)
private Bitmap resizeImg (int rsm) {
Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght);
return bmp;
}
I need to use Matrix as the scaling of Imageview. But it's not the size I want. It works right without the Matrix.
I'm solving the Matrix problem like this:
Bitmap.createScaledBitmap
private Bitmap resizeImg (int rsm) {
Bitmap bmp = decodeSampledBitmapFromResource(getResources(),rsm,wdth,hght);
// return bmp;
Bitmap resized = Bitmap.createScaledBitmap(bmp, wdth,hght,true); //I get OutOfMemoryError this line.
return resized;
}
This insertion really solves my problem. But every day I get lots of OutOfMemoryError errors.
What do I need to do to fix this error? Please help me. Thank you.

1] Add largeHeap as true in android manifest to your application tag:
android:largeHeap="true"
2] Recycle your all used bitmaps,
Example:
bmp.recycle();
resized.recycle();

Related

Bitmap color code change after scaledown

I have one image which have color code of #AAA28B (170R,162G,139B). Now let's say current image size is 1200x1200 now I want to make it scale down at 600x600 so i use below code and get resulted in bitmap but the problem is its bitmap color code change to #ABA38C, So it RGB values increase to plus one compare to original image color and become (171R,163G,140B) how to prevent this?.
See attach a screenshot where the first image if original loaded directly from android drawable and other it loads by using following code.
private void loadImage(int width, int height){
Bitmap bitMapTest=BitmapFactory.decodeResource(getResources(),R.drawable.ic_test);
Log.i("IMAGE","Image format is"+ bitMapTest.getConfig().name()+
"Image size is"+ bitMapTest.hasAlpha() + "bitmap size is"+ bitMapTest.getHeight());
Bitmap decodeBitmap=decodeSampledBitmapFromResource(getResources(),R.drawable.ic_test,width,height);
Log.i("IMAGE","Image format is"+ decodeBitmap.getConfig().name()+
"Image size is"+ decodeBitmap.hasAlpha() + "bitmap size is"+ decodeBitmap.getHeight());
//adjust of alha deos not give me any help result remain same
//decodeBitmap=adjustOpacity(decodeBitmap);
mImgView.setImageBitmap(decodeBitmap);
}
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;
options.inPreferredConfig= Bitmap.Config.ARGB_8888;
options.inScaled=false;
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 = 2;
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;
}
Here is orginal image :-
It seems like applying following code for scaledown working fine for the solid image like this.
Bitmap decodeBitmap=Bitmap.createScaledBitmap(sourceBitmap,width,height,false/*Make sure filter is false*/);

How to set fullHD image to ImageView

I want to set a fullHD(1080x1920) image to ImageView.
I have searched but no efficient method.
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 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;
Log.d("DUE","Options height: " + height + " - width: " + width);
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;
}
Or:
private Bitmap resize(int resId, int width, int height){
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId, bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
if (heightRatio > 1 || widthRatio > 1)
{
if (heightRatio > widthRatio)
{
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}else{
}
bmpFactoryOptions.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeResource(getResources(), resId, bmpFactoryOptions);
return bitmap;
}
I want to display the original image size, without reducing the size of image
Can you help me?
Thanks all!
You can use image loading libraries like Universal Image Loader, Fresco.
1) https://github.com/nostra13/Android-Universal-Image-Loader
2) https://github.com/facebook/fresco
3) https://guides.codepath.com/android/Displaying-Images-with-the-Fresco-Library
Both examples you posted are useful to reduce the image size (i.e. to save memory).
I want to display the original image size, without reducing the size of image
If you only want to set a image from resources, there are much simpler alternatives.
Assing the image in code to an ImageView:
ImageView img;
img.setImageResource(R.drawable.image);
Or create a Bitmap from your Resource:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Or set your image in xml:
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image"
android:scaleType="center"/>
you can use glide
Glide is a fast and efficient open source media management and image loading framework for Android that wraps media decoding, memory and disk caching, and resource pooling into a simple and easy to use interface.
full documantation
Downloading custom sizes with Glide allow to add hight & width of iamge
Glide's ModelLoader interface provides developers with the size of the view they are loading an image into and allows them to use that size to choose a url to download an appropriately sized version of the image.
Using appropriately sized image saves bandwidth, storage space on the device, and improves the performance of the app.

Android ImageView XML no leak vs BitmapFactory.decodeResource leak ?

Getting OOM big time in my game UI (I'm only targeting kitkat and above)
I noticed that if I use a android:src="#drawable/empty_screen_game_setup" in XML, leaving and entering the activity always has the same memory usage.
If I DON'T set src in XML, but rather use the following google code, leaving and entering the activity makes the memory usage climb like crazy. This is a test app with no other code because I'm trying to understand the OOM. So much conflicting info out there!!
Is it better to just use src in XML memory-wise? I was hoping to use one set of ressources in no-dpi and scale them to size with bitmapfactory given the screen size but I guess that's not best :(
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);
}
And in onCreate:
glass = (ImageView) findViewById(R.id.imageViewGlass);
glass.setImageBitmap( decodeSampledBitmapFromResource(getResources(), R.drawable.empty_screen_game_setup, 500, 300) );

Scaling down Images in android

I am implementing an application in which an activity shows a image view with full screen. Now i have some images downloaded in application's file directory. I want to set image to image view in that activity for which i am scaling down the larger images. I am getting OutOfMemory error after 10 to 15 mins of using application. error is in decodeFile of BitmapFactory. Here is my code :
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;
}
public static Bitmap decodeSampledBitmapFromFile(String imagePath,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imagePath, options);
}
Right now i am giving reqHeight = 500 and reqWidth = 500
This code is given in Android guidelines page. Is there anything i am missing, if so please help me out. I tried lots of things but not getting any solution.
Change you int inSampleSize = 1; to int inSampleSize = 2 or 3 and test the application again, I hope this will solve your problem. I also suggest insted of this technique,try lazy loading for all you image dowanload by doing so there will be no bitmap and outOfMemoryError. Yo can have lazy loading - https://github.com/thest1/LazyList
Try using this
Bitmap resizedbitmap2 = Bitmap.createScaledBitmap(your_bitmap, width, height,
true);
it will help you.
There might be a memory leak in your app if you are storing list of bitmaps returned by decodeSampledBitmapFromFile somewhere. Try to check for memory leak and also use Bitmap.recycle() to recycle bitmaps and help android free memory.

Out of memory error due to large bitmap size

I am using some static images in my application and the images is being kept in the drawable folder.The size of the images are near about 2 MB but I have scaled them properly but still it is showing out of memory error due to the bitmap size during run time.And this is specially for samsung galaxy s3.
Can anybody plz tell me how to stop this and to reduce the bitmap size.
I have tried using this code for recycling images:
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 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 = 8;
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;
}
First compress the images to check if actually these are the ones that leak memory.
Get used to using tools to measure memory you are using and finding leaks because simply this is a way to do it.
You might start here:
What Android tools and methods work best to find memory/resource leaks?
I also recomend this code for image viewing
https://github.com/nostra13/Android-Universal-Image-Loader

Categories

Resources