Memory efficient image resize in Android - android

I am trying to reduce the size of images retrieved form the camera (so ~5-8 mega pixels) down to one a a few smaller sizes (the largest being 1024x768). I Tried the following code but I consistently get an OutOfMemoryError.
Bitmap image = BitmapFactory.decodeStream(this.image, null, opt);
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();
// Constrain to given size but keep aspect ratio
float scaleFactor = Math.min(((float) width) / imgWidth, ((float) height) / imgHeight);
Matrix scale = new Matrix();
scale.postScale(scaleFactor, scaleFactor);
final Bitmap scaledImage = Bitmap.createBitmap(image, 0, 0, imgWidth, imgHeight, scale, false);
image.recycle();
It looks like the OOM happens during the createBitmap. Is there a more memory efficient way to do this? Perhaps something that doesn't require me to load the entire original into memory?

When you decode the bitmap with the BitmapFactory, pass in a BitmapFactory.Options object and specify inSampleSize. This is the best way to save memory when decoding an image.
Here's a sample code Strange out of memory issue while loading an image to a Bitmap object

Are you taking the picture with the camera within your application? If so, you should set the picture size to a smaller one in the first place when they're being captured via android.hardware.Camera.Parameters.setPictureSize

Here is a similar question that I answered and show how to go about dynamically loading the proper image size.
out of memory exception + analyzing hprof file dump

Related

How to get scaled bitmap with respect to screen size with out getting Out of memory exception

In my activity I am creating a Bitmap of the width and height same as the device resolution (width and height )
what I am doing
Bitmap mBitmap = Bitmap.createBitmap(screenWidth, screenHeight,
Bitmap.Config.ARGB_8888);
and screenWidth and screenHeight is
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
Now if I make this bitmap I get my heap goes up to 19mb , which is not so good.
So tell me 2 things
1. What is a good way of creating the bitmap with respect to screen with and height with minimum memory consumed
2. How can I destroy the bitmap after using it ?
Please provide me a little source code or link of source code.
What is a good way of creating the bitmap with respect to screen with and height with minimum memory consumed ?
Never ever create a Bitmap with the screen height or width, because that will be very huge based on the density of the device.Instead use the height and width of the screen and calculate the aspect ratio. Now fix the height to a constant value (like 1200px) and then calculate the width based on the aspect ratio. The ImageView or any other view will scale this properly.
If you really want transparency then use Bitmap.Config.ARGB_8888, if not could use RGB_565 or something else from the list here: http://developer.android.com/reference/android/graphics/Bitmap.Config.html
Follow below points if you are not creating a fresh bitmap but decoding the bitmap from some resource:
You need to use BitmapFactory.Options.inSampleSize to reduce the sampling. So how to calculate the inSampleSize if you already know the height and width? Refer this here: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
So you do all this, and still the inSampleSize is not high enough and you get the OutOfMemoryError ? Don't worry, if this is the case, you need to catch this OutOfMemoryError and in that increase your inSampleSize and do the bitmap decode again. Put this logic in a loop, so the crash never happens.
How can I destroy the bitmap after using it ?
This is really simple. Make sure to call the Bitmap.recycle() method. And remove all reference to the bitmap. Once you do this, the resource will be released and GC will do the cleaning up.
UPDATE: When you create the a bitmap with screen_width and screen_height you would end up with a huge bitmap. Instead create a less resolution bitmap that fits the whole screen. You can see the following code on how this is done.
float screenHeight = displaymetrics.heightPixels;
float screenWidth = displaymetrics.widthPixels;
float aspectRatio = screenWidth/screenHeight;
int modifiedScreenHeight = 1000;
int modifiedScreenWidth = (int) (modifiedScreenHeight * aspectRatio);
Bitmap mBitmap = Bitmap.createBitmap(modifiedScreenWidth, modifiedScreenHeight, Bitmap.Config.ARGB_8888);
Now you got the bitmap with the right aspect ratio. You could use this bitmap as it is in the ImageView to fill the whole screen. Make sure you put android:scaleType="fitXY" for the ImageView.

Scale Bitmap lower than 4096x4096

I am currently working on an application that shows a Bitmap on an ImageView. Now the problem is, whenever trying to show a Bitmap larger than 4096x4096, it simply won't show up, stating that the image is too large to be shown.
For example: I want to load up an image that's 4128x2322 pixels
I to resize it to be smaller than 4096x4096.
I thought about something like this:
Bitmap bitmap;
if(b.getHeight() >= 4096) {
double f = b.getHeight() / 4096;
b = Bitmap.createScaledBitmap(b, (int)(b.getWidth() / f), (int)(b.getHeight() / f), false);
}else if(b.getWidth() >= 4096) {
double f = b.getWidth() / 4096;
b = Bitmap.createScaledBitmap(b, (int)(b.getWidth() / f), (int)(b.getHeight() / f), false);
}
imageview.setImageBitmap(b);
Somehow it won't work...
Any advices on how to scale properly?
Thanks in advance!
I got an intent which takes a picture and returns the image
That image will be stored somewhere else, which you will reference via a File or perhaps a content: Uri.
But to show the taken picture I need to scale it down first
Use BitmapFactory to load the bitmap. Use BitmapFactory.Options and its inSampleSize field to indicate how you want the image to be downsampled. This is covered in the documentation.
There is no device with resolution 4096X4096, your image going to be scaled any way. So instead trying to scale it up just top let the system to scale it down. How about taking the screen size in to calculation and provide the final scale by your self. Not only that you will save space but also improve performance.

Android - How to enlarge a bitmap

I usually download images that are larger in size and shrink them using an imageview but lately Im trying to deal with my apps not working on a lesser network connection so I was wondering how can I increase the size of an image once it gets to the device. I tried resizing the image once it was in an imageview but the imageview will get no larger than the original image. Im sure theres a really easy way to increase or blow up an image on the device but I havent come across it yet.
So.....how can I increase the size of an image. Id like to blow it up and use it in an imageview but the images Im dealing with are only 128X256 and Id like to expand them to about 512X1024.
Try using this method:
public static Bitmap scaleBitmap(Bitmap bitmapToScale, float newWidth, float newHeight) {
if(bitmapToScale == null)
return null;
//get the original width and height
int width = bitmapToScale.getWidth();
int height = bitmapToScale.getHeight();
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(newWidth / width, newHeight / height);
// recreate the new Bitmap and set it back
return Bitmap.createBitmap(bitmapToScale, 0, 0, bitmapToScale.getWidth(), bitmapToScale.getHeight(), matrix, true); }
refer to my answer in: ImageView OutofMemoryException
Use matrix to resize the bitmap.
Check this
Resize Bitmap
If you want to scale the Bitmap manually, there is a Bitmap.createScaledBitmap() method that you can use for this.
If you want the ImageView to handle this, you have to set the layout_width/layout_height to something other than wrap_content or it will always shrink to the size of the Bitmap. Then you need to change the scaleType attribute to a type that actually scales the bitmap.
The functionality to scale image up or down is readily available via android.graphics library:
Bitmap bitmapScaled = Bitmap.createScaledBitmap(Bitmap bitmapOrig, int widthNew, int heightNew, boolean filter);

Image from resources is scaled properly but image blob from SQlite isn't - Android

I am running into a strange issue. I have multiple images in my Android project which I stored as .png files under res\drawable. I was able to easily extract the images at runtime and convert them to a bitmap like this:
Drawable d = getResources().getDrawable(R.drawable.imageId);
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
This works great and the image gets scaled correctly no matter what screen density the device has. All my images are 200 pixels by 200 pixels and my image layout is configured as 200 dip x 200 dip.
Now, I have stored all images as blobs in an SQlite database due to scalability issues and I am extracting them at runtime and converting to a bitmap like this:
byte[] bb = cursor.getBlob(columnIndex);
Bitmap bitmap = BitmapFactory.decodeByteArray(bb, 0, bb.length);
The image displays fine if the screen density is standard 160 dip. But if the density is any less or more, the image doesn't scale and remains 200 pixels x 200 pixels for 160 dip. So basically, on a smaller screen (120 dip), the image takes more space than it should and on a larger screen (240 dip), it takes less space than it should.
Has anyone else run into this bizarre issue? Any explanation, workaround, solution will be really appreciated.
Thanks much in advance!
Okay, I finally got it to work by using createScaledBitmap().
After creating a bitmap from the blob, I calculate the scaling factor and then calculate the new width and height. I then use those in the createScaledBitmap() function. Here's the code that works:
public static Bitmap getImageFromBlob(byte[] mBlob)
{
byte[] bb = mBlob;
Bitmap b = BitmapFactory.decodeByteArray(bb, 0, bb.length);
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int newWidth = b.getWidth()*metrics.densityDpi)/DisplayMetrics.DENSITY_DEFAULT;
int newHeight = b.getHeight()*metrics.densityDpi)/DisplayMetrics.DENSITY_DEFAULT;
return Bitmap.createScaledBitmap(b, newWidth, newHeight, true);
}
This link provided the clue:
difference between methods to scale a bitmap
Use decodeByteArray(byte[] data, int offset, int length, BitmapFactory.Options opts) and in opts set inDesity to let say 160.
Worked for me, see this. But I have to say, I think SQLite is doing it right, and the android drawable is incorrectly sized.

Scaling image in Android

I tried to scale an high-resolution image to the desired size of my android and then set it as wallpaper, but as result I have a scaled image with 'annoying alternate rows' that make the picture NOT attractive.
int newWidth = wallpaperManager.getDesiredMinimumWidth();
int newHeight = wallpaperManager.getDesiredMinimumHeight();
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmapOrg, newWidth, newHeight, true);
You are scaling the bitmap correctly.
You could try downloading GIMP (free software) and scale your image to match the main 3 resolutions of android phones. This may produce a better result.

Categories

Resources