Does this procedure takes too much RAM while creating + scaling a Bitmap? - android

I have an "init" procedure that fill the contents of a array of Bitmaps (a "cache"), reading pixels from a single, big, int array.
Before saving each one of them, images could need to be resized to a "target" dimension. So I have to first create the full size Bitmap with Bitmap.createBitmap, then save it in the cache using Bitmap.createScaledBitmap.
Obviously I don't want to fill up the memory, but it happens "sometimes" during the procedure. What I'm missing? I'm wondering if the first Bitmap created with Bitmap.createBitmap is actually deleted just after the setImageCache function, or not.
for (int i = 0; i < array.length; i++) {
setImageCache(i, Bitmap.createScaledBitmap(
Bitmap.createBitmap(intArray, area * i, origW, origW, origH, Bitmap.Config.ARGB_8888),
targetW, targetH, true
));
}

As long as you don't get OutOfMemoryExceptions everything should be fine, but you can improve your code by recycling not needed bitmaps like this:
for (int i = 0; i < array.length; i++) {
Bitmap bitmap = Bitmap.createBitmap(intArray, area * i, origW, origW, origH, Bitmap.Config.ARGB_8888);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, targetW, targetH, true);
bitmap.recycle();
setImageCache(i, scaledBitmap);
}
By recycling bitmaps you don't need you release the memory taken up by those not needed bitmaps and that can significantly curb memory problems when dealing with large images.

Related

Set all black in image to another color (ImageView/Bitmap)

I'm trying to convert all the black pixels in one Bitmap (Created from an ImageView that was a PNG file)..
I've tried it in many ways but I still couldn't succeed in that.
Please help me I'm trying it for like 3 days straight...
A little example of my code:
headSkin.buildDrawingCache();
final Bitmap bmp = headSkin.getDrawingCache();
int w = bmp.getWidth();
int h = bmp.getHeight();
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
int color = bmp.getPixel(x, y);
// Shift your alpha component value to the red component's.
bmp.setPixel(x, y, Color.RED);
}
}
As you can see... I didn't even state an IF statement..
I just tried to make all the pixels red in this bitmap and even this didn't work.. pls help?
I see 2 problems here,
First, you have this Bitmap object in your memory, and you change the black pixels to red, but how do you know if it is changed or not? You should set an ImageView to this Bitmap to see the result (or save it to file etc.)
Second, use getPixels and setPixels instead, getPixels will give you 1 dimensional array, it goes like 1.row, 2.row, 3.row etc. And setPixels also accepts a 1 dimensional array. This function is incredibly faster than altering pixels 1 by 1.
#Anil
Hi dude, just tried it and I can't use it 'cuz of IndexOutOfBound exception...
headSkin.buildDrawingCache();
bmp = headSkin.getDrawingCache();
int [] allpixels = new int [bmp.getHeight()*bmp.getWidth()];
bmp.getPixels(allpixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
for(int i = 0; i < allpixels.length; i++)
{
if(allpixels[i] == Color.BLACK)
{
allpixels[i] = Color.RED;
}
}
bmp.setPixels(allpixels, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());
headSkin.setImageBitmap(bmp);
what is the problem here?
EDIT: Just tried it now while running, not debugging and it doesn't even show me an error or something.. It just makes about 1-2 single pixels red in this whole bitmap
headSkin.buildDrawingCache();
final Bitmap bmp = headSkin.getDrawingCache();
I think you have problem on these lines. The rest of the code looks fine.
Maybe the bitmap is not initialized, so you only have a Bitmap reference, instead of Bitmap object with data inside.
Can you delete the bitmap part from your code and initialize Bitmap like this:
Bitmap myBitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.RGB8888);
and then perform pixel operations like you did above, just set all the pixels to same color.

Why do I NOT get an out of memory exception?

I have a high resolution image (2588*1603) in drawable folder. If I use below code (1) to set it for the imageView I do not get OOM exception and the image assigned as expected:
public class MainActivity extends ActionBarActivity{
private ImageView mImageView;
int mImageHeight = 0;
int mImageWidth = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageView = (ImageView) findViewById(R.id.imageView);
mImageView.setScaleType(ScaleType.FIT_CENTER);
BitmapFactory.Options sizeOption = new BitmapFactory.Options();
sizeOption.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.a, sizeOption);
mImageHeight = sizeOption.outHeight;
mImageWidth = sizeOption.outWidth;
mImageView.post(new Runnable() {
#Override
public void run() {
try {
BitmapRegionDecoder bmpDecoder = BitmapRegionDecoder
.newInstance(getResources().openRawResource(R.drawable.a),true);
Rect rect = new Rect(0,0,mImageWidth, mImageHeight);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inDensity = getResources().getDisplayMetrics().densityDpi;
Bitmap bmp = bmpDecoder.decodeRegion(rect, options);
mImageView.setImageBitmap(bmp);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Note that rect size is exactly the same as image size.
But If I use other methods like for example 2 or 3 I get OOM.
2) mImageView.setBackgroundResource(R.drawable.a);
3) Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a);
mImageView.setImageBitmap(bmp);
What is the difference between 1 and 2,3 ?
(I know how to solve OOM, I just want to know the difference)
This is the source of BitmapRegionDecoder#decodeRegion:
public Bitmap decodeRegion(Rect rect, BitmapFactory.Options options) {
checkRecycled("decodeRegion called on recycled region decoder");
if (rect.left < 0 || rect.top < 0 || rect.right > getWidth()
|| rect.bottom > getHeight())
throw new IllegalArgumentException("rectangle is not inside the image");
return nativeDecodeRegion(mNativeBitmapRegionDecoder, rect.left, rect.top,
rect.right - rect.left, rect.bottom - rect.top, options);
}
As you can see, it simply calls a native method. I do not understand enough C++ to see whether the method scales the bitmap down (according to your inDensity flag).
The other two methods use the same native method (nativeDecodeAsset) to get the bitmap.
Number 2 caches the drawable and thus needs more memory. After lots of operations (checking if the bitmap is already preloaded or cashed and other things), it calls a native method to get the bitmap. Then, it caches the drawable and sets the background image.
Number 3 is pretty straight forward, it calls a native method after a few operations.
Conclusion: For me, it is hard to say which scenario applies here, but it should be one of these two.
Your first attemp scales the bitmap down (the inDensity flag) and thus needs less memory.
All three methods need more or less the same amount of memory, number 2 and 3 just a little bit more. Your image uses ~16MB RAM, which is the maximum heap size on some phones. Number 1 could be under that limit, while the other two are slightly above the threshold.
I suggest you to debug this problem. In your Manifest, set android:largeHeap="true" to get more memory. Then, run your 3 different attemps and log the heap size and the bytes allocated by the bitmap.
long maxMemory = Runtime.getRuntime().maxMemory();
long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long freeMemory = maxMemory - usedMemory;
long bitmapSize = bmp.getAllocationByteCount();
This will give you a better overview.
Ok, down to core, single difference between 1 and 2,3 is that 1 doesn't support nine patches and purgeables. So most probably a bit of additional memory allocated for NinePatchPeeker to work during decoding is what triggers OOM in 2 and 3 (since they use same backend). In case of 1, it isn't allocated.
Other from that i don't see any other options. If you look at image data decoding, then tiled decoding uses slightly more memory due to image index, so if it was the case, situation would be opposite: 1 will be throwing OOMs and 2,3 is not.
Too many detail of the picture results the out of memory.
summary: 1 use the scaled bitmap; 2,3 load the full detailed drawable(this results the out of memory) then resize and set it to imageview.
1
Bitmap bmp = bmpDecoder.decodeRegion(rect, options);
the constructor(InputStream is, boolean isShareable) use the stream , which will not exhaust the memory.
use BitmapFactory.Options and BitmapRegionDecoder will scale down the bitmap.
Refer: BitmapRegionDecoder will draw its requested content into the Bitmap provided, clipping if the output content size (post scaling) is larger than the provided Bitmap. The provided Bitmap's width, height, and Bitmap.Config will not be changed
2,3
Drawable d = mContext.getDrawable(mResource);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a);
there is no scale option, the whole picture will load to memory
Sorry for English.
Maybe help you.
You are not getting OOM exception because of this
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
It is already given here
public Bitmap.Config inPreferredConfig
Added in API level 1
If this is non-null, the decoder will try to decode into this internal configuration. If it is null, or the request cannot be met, the decoder will try to pick the best matching config based on the system's screen depth, and characteristics of the original image such as if it has per-pixel alpha (requiring a config that also does). Image are loaded with the ARGB_8888 config by default.

Loading a jpeg using BitmapRegionDecoder gives checkerboard distortion

I'm loading a big jpeg file from a url using an InputStream from a URLConnection. The goal is to get an int[] with the image data as this is more efficient than using a Bitmap for further use. There are two options here.
The first is to create a Bitmap object and to copy the results in an int[]. This works in my application but the full image is in memory twice upon loading as the image data is copied into the int[] image.
Bitmap full = BitmapFactory.decodeStream(conn.getInputStream());
full.getPixels(image, 0, width, 0, 0, width, height);
To save memory, I'm trying to perform this process in a tiled fashion using a BitmapRegionDecoder.
int block = 256;
BitmapRegionDecoder decoder = BitmapRegionDecoder.
newInstance(conn.getInputStream(), false);
Rect tileBounds = new Rect();
// loop blocks
for (int i=0; i<height; i+=block) {
// get vertical bounds limited by image height
tileBounds.top = i;
int h = i+block<height ? block : height-i;
tileBounds.bottom = i+h;
for (int j=0; j<width; j+=block) {
// get hotizontal bounds limited by image width
tileBounds.left = j;
int w = j+block<width ? block : width-j;
tileBounds.right = j+w;
// load tile
tile = decoder.decodeRegion(tileBounds, null);
// copy tile in image
int index = i*width + j;
tile.getPixels(image, index, width, 0, 0, w, h);
}
}
Technically this works and I get the full image in the int[] image. Also the tiles are seemlessly inserted into the image.
Now my problem. The second method results in an image which has some kind of strange checkerboard distortion. Pixels seem to alternate between being slightly darker or slightly lighter. BitmapRegionDecoder is supposed to support jpeg, and BitmapFactory.decodeStream has no problems. What is the problem here?
Found it! apparently if you feed null into decoder.decodeRegion(tileBounds, null); it returns a Bitmap with quality Bitmap.Config.RGB_565 (not sure if this is device dependant). Simply feeding it a new options set returns a Bitmap of Bitmap.Config.RGB_ARGB8888 quality. By default this preferred quality is set.
BitmapFactory.Options options = new BitmapFactory.Options();
...
// load tile
tile = decoder.decodeRegion(tileBounds, options);
Thanks for your self-investigation!
Though I would recommend avoid relying on some default and make it clear:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig=Config.ARGB_8888; //explicit setting!
result_bitmap=regionDecoder.decodeRegion(cropBounds, options);
Thanks!

OutOfMemory when inverting a bitmap?

I'm having the OutOfMemory error when inverting a bitmap.. Here is the code I use to invert:
public Bitmap invertBitmap(Bitmap bm) {
Bitmap src = bm.copy(bm.getConfig(), true);
// image size
int height = src.getHeight();
int width = src.getWidth();
int length = height * width;
int[] array = new int[length];
src.getPixels(array, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());
int A, R, G, B;
for (int i = 0; i < array.length; i++) {
A = Color.alpha(array[i]);
R = 255 - Color.red(array[i]);
G = 255 - Color.green(array[i]);
B = 255 - Color.blue(array[i]);
array[i] = Color.argb(A, R, G, B);
}
src.setPixels(array, 0, src.getWidth(), 0, 0, src.getWidth(), src.getHeight());
return src;
}
The image is ~80 kb big, the dimensions are 800x1294 and the picture has words which are black and an invisible background..
The images are in a ViewPager..
when you copy bm, try: bm = null;
In android , due to 16MB (on almost all phones) memory cap for applications, it is not wise to hold entire bitmap in memory. This is a common scenario and is happening to may developers.
You can get many information about this problem in this stackoverflow thread. But I really urges you to read android's official document about efficient usage of Bitmaps. They are here and here.
The memory size used by an image in completelly different from the file size of that image.
While in a file the image may be compressed using different alghorithms (jpg, png, etc.) and when loaded in memory as a bitmap, it uses 2 or 4 bytes per pixel.
So in your case (you are not sowing the code but it lloks like you are using 4 bytes per pixel), the memory size per image is:
size = width * height * 4; // this is aprox 2MB
In your code, first you copy the original bitmap to a new one, and then ceate an array to manipulate the colors. So in total you are using size x 3 = 6MB per image inversion.
There are plenty of examples on how to handle large bitmap in Android, but I'll leave you what I think is the most important topics:
Try to use only one copy of bitmap in your code above
If you are only having words in your image use Bitmap.Config = RGB_565. This only uses 2 bytes per pixel, reducing size by half.
Call recycle() on a bitmap that you don't need anymore.
Have a lool at scale option in Bitmap.Factory. You may reduce the size of image that still fit your needs.
good luck.

Android: How to use a large amount of Bitmaps?

I am drawing a frame by frame animation to a canvas and I have about 100 pics that I'm using to do this (which is about 1.5MB total). I started out by just doing this:
s000 = BitmapFactory.decodeResource(getResources(), R.drawable.s0);
s001 = BitmapFactory.decodeResource(getResources(), R.drawable.s1); ...etc...
to every image and then drawing each image to the canvas:
c.drawBitmap(s000, X, Y, null);
to make an animation.
The problem is that I get this error "OutOfMemoryError: bitmap size exceeds VM budget". How would I load all the pics without getting this error? Is 1.5MB to much memory or do I have a memory leak? What would I do to fix the memory leak?
Thank you very much for your help. I am noob with android so could you please leave examples and not just tell me to do something that I wont understand :) Thanks again
Try like this for every frame you draw:
s000 = BitmapFactory.decodeResource(getResources(), R.drawable.s0);
c.drawBitmap(s000, X, Y, null);
s000.recycle();
s000 = null;
This will try to release the memory after drawing the frame.
EDIT
myImgLen = 30;
Bitmap bitmap = null;
for (int i = 0; i < myImgLen; i++) {
bitmap = BitmapFactory.decodeResource(getResources(), getResource‌​s().getIdentifier("s" + i, "drawable", getPackageName()));
c.drawBitmap(bitmap, X, Y, null);
bitmap.recycle();
bitmap = null;
}
Store your image into res->drawable-xhdpi make folder inside res folder.
For more information see this link http://developer.android.com/guide/practices/screens_support.html.
Maybe the sizes of the images are incorrect. Refer to this answer: Strange out of memory issue while loading an image to a Bitmap object.

Categories

Resources