Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


[android] out of memory when loading images


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
6 replies to this topic

#1 sheep19   Members   -  Reputation: 413

Like
0Likes
Like

Posted 03 September 2012 - 09:33 AM

I'm making a game for android. It is 2D and uses the android graphics toolkit (not OpenGL ES).

My game entities consist of several frames that are updated as time passes. Each frame is a different image.

Note that I'm not using the Bitmap class directly, but a wrapper I made called "GreenBitmap". It has a Bitmap inside and uses reference counting to reuse it when needed (so that it will not be loaded more than once). So for example if I have three Actors, the frames for all of them will be loaded only once and reused.

package com.greenbits.RiverCross;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.util.SparseArray;
public class GreenBitmap
{
private static SparseArray<Entry> map = new SparseArray<Entry>();

public Bitmap bitmap;
private int id;

/**
  * @param drawableID The ID of the image
  * @return The width of the image
  */
public static float getBitmapWidth(Resources res, int drawableID)
{
  BitmapFactory.Options o = new BitmapFactory.Options();
  o.inJustDecodeBounds = true;
 
  BitmapFactory.decodeResource(res, drawableID, o);
  return o.outWidth;
}

/**
  * @param drawableID The ID of the image
  * @return The height of the image
  */
public static float getBitmapHeight(Resources res, int drawableID)
{
  BitmapFactory.Options o = new BitmapFactory.Options();
  o.inJustDecodeBounds = true;
 
  BitmapFactory.decodeResource(res, drawableID, o);
  return o.outHeight;
}

public GreenBitmap(Resources res, int drawableID)
{
  id = drawableID;
  Entry e = null;
 
  // if the ID doesn't exist (i.e the bitmap isn't stored), load it
  if( (e = map.get(drawableID)) == null )
  {
   bitmap = BitmapFactory.decodeResource(res, drawableID); // load the bitmap
   e = new Entry(bitmap, 1); // create a new entry
   map.put(drawableID, e); // put it in the map
  }
  else
  {
   bitmap = e.bitmap;
   ++e.count;
  }
}

public GreenBitmap(Resources res, int drawableID, int requiredWidth, int requiredHeight)
{
  // first use Options with inJustDecodeBounds to get the image's dimensions
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inJustDecodeBounds = true;
 
  BitmapFactory.decodeResource(res, drawableID, options);
 
  // calculate inSampleSize
  options.inSampleSize = calculateInSampleSize(options, requiredWidth, requiredHeight);
  options.inJustDecodeBounds = false;
 
  id = drawableID;
  Entry e = null;
 
  // if the ID doesn't exist (i.e the bitmap isn't stored), load it
  if( (e = map.get(drawableID)) == null )
  {
   bitmap = BitmapFactory.decodeResource(res, drawableID, options); // load the bitmap
   e = new Entry(bitmap, 1); // create a new entry
   map.put(drawableID, e); // put it in the map
  }
  else
  {
   bitmap = e.bitmap;
   ++e.count;
  }
}

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;
}

/**
  * @return The internal Bitmap object. You can also use the public 'bitmap' member.
  */
public Bitmap get()
{
  return bitmap;
}

public void recycle()
{
  Entry e = map.get(id);
  --e.count;
 
  //Log.e("GreenBitmap", "count of ID " + id + " was lowered to " + e.count);
 
  if( e.count == 0 )
  {
   e.bitmap.recycle();
   map.remove(id);
  
   //Log.e("GreenBitmap", "Bitmap " + id + " was recycled");
  }
}

private static class Entry
{
  public Bitmap bitmap;
  public int count;
 
  public Entry(Bitmap _b, int _c)
  {
   bitmap = _b;
   count = _c;
  }
}
}

I'm also calculating how many samples to use to reduce memory consumption.


Here's the problem. I have a class named "Human" that has 20 frames of animation. The frames are only a few KB big. On the emulator the game runs, but it gives me OutOfMemoryException (or Error, I don't remember) on HTC One X (!).

I've read somewhere that images aren't stored on the garbage collected heap (which is guaranteed to be 16MB) but on a different, native heap that has limited memory.

Does anyone know what I can do to solve this? Why does it run on the emulator and not on a top class phone?
Is there a way to load the images in the garbage collected heap?

Thanks.

Sponsor:

#2 frob   Moderators   -  Reputation: 22693

Like
0Likes
Like

Posted 03 September 2012 - 05:50 PM

What is your exact error message? Is it "java.lang.OutOfMemoryError: bitmap size exceeds VM budget" ?

If so, there are thousands of other web pages on StackOverflow explaining many different ways to get it and many different ways to handle it.

I'm guessing your code elsewhere is either making unnecessary copies of the resources, or else you are leaking resources elsewhere.


If it isn't that message, are you attempting to load all the images into main memory, or into OpenGL? Graphics memory is generally limited and precious. Generally keep stuff unloaded if reasonable or in main memory if you really need it, and out of graphics memory until it is essential for display.

Those are a few thoughts as to the reason behind it.

Post the exact error message when you get it. That will help a lot.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I write about assorted stuff.


#3 sheep19   Members   -  Reputation: 413

Like
0Likes
Like

Posted 06 September 2012 - 03:52 AM

What is your exact error message? Is it "java.lang.OutOfMemoryError: bitmap size exceeds VM budget" ?

If so, there are thousands of other web pages on StackOverflow explaining many different ways to get it and many different ways to handle it.

I'm guessing your code elsewhere is either making unnecessary copies of the resources, or else you are leaking resources elsewhere.


If it isn't that message, are you attempting to load all the images into main memory, or into OpenGL? Graphics memory is generally limited and precious. Generally keep stuff unloaded if reasonable or in main memory if you really need it, and out of graphics memory until it is essential for display.

Those are a few thoughts as to the reason behind it.

Post the exact error message when you get it. That will help a lot.


That is exactly the message.

I do not attemp to load *all* images in main memory - I'm not using openGL.
I attemp to load all images that a certain game level needs - which is logical and natural. I can't be loading images in the update() loop.

I have already searched on google and stack overflow. What people say is:
1) Use lower resolution images.
2) Calculate how many samples are needed (I'm doing it).

By the way I managed to solve the problem! I noticed that some frames of the animations where actually the same picture, so I erased the duplicate ones.
For example if an animation had 3 frames, frame_0.png, frame_1.png, frame_2.png
frame_0.png and frame_1.png sometimes where the same - so I deleted frame_1.png and used frame_0.png twice. That saved me a lot of memory.

Also some images had a very big resolution (700x400 and was drawn at 200x100 for example), so I resized those as well.

I'm also aware that png images consume width x height x 4 bytes when loaded into memory - but I guess I can't do anything about that.


I've got another question:
As I am not using OpenGL, does it mean that the images I load are stored into main memory (RAM) instead of video memory (VRAM)?
If I used OpenGL, would the images be stored in video memory? If yes, I guess that just by using openGL huge (main) memory savings could be made.

What about games that are done by professionals? Some games have a lot of images, 3D models etc and they don't have memory problems (?). Are there techniques I should know?

Thanks

#4 rockseller   Members   -  Reputation: 121

Like
0Likes
Like

Posted 06 September 2012 - 10:42 AM

...

I've got another question:

As I am not using OpenGL, does it mean that the images I load are stored into main memory (RAM) instead of video memory (VRAM)?
If I used OpenGL, would the images be stored in video memory? If yes, I guess that just by using openGL huge (main) memory savings could be made.

What about games that are done by professionals? Some games have a lot of images, 3D models etc and they don't have memory problems (?). Are there techniques I should know?

Thanks





I strongly recommend you switching to OpenGL ES 1.0 or 2.0.

As for your last questions:
Your bitmaps are stored on the RAM, not the VRAM.

Your java code runs as compiled ByteCode on the Dalvik Virtual Machine.

1)Every object and variable is stored on the HEAP, which is the memory that the MOBILE has.

2)The only way you can store stuff on the VRAM, that would be by using the existing interface between the CPU an GPU, and that is by a library such as OpenGL ES.
OpenGL uses buffers which stores vertices information that can be used for several purposes (drawing), and since you are not using OpenGL, you won't ever touch the VRAM.

3)If you use OpenGL, you don't know how much memory you will save until you profile (test) your game on a certain real device.


4)About the professional games, the best answer I can give you right now is, that Images are stored in a PIXEL format on BUFFERS (Array of numbers) sent to OpenGL using a library, it is send as a texture, once that happens, you can delete any references to the recently created BITMAP, freeing memory from the CPU, and leaving the memory usage to the OpenGL GPU or CPU (don't focus on this right now, VBOs/FBOs).


5) OpenGL might seem hard at first, and it is, but you are smart enough to learn it ;).

Just watch some tutorials, and stick to Java.

#5 Ameise   Members   -  Reputation: 766

Like
0Likes
Like

Posted 25 October 2012 - 01:51 PM


...

I've got another question:

As I am not using OpenGL, does it mean that the images I load are stored into main memory (RAM) instead of video memory (VRAM)?
If I used OpenGL, would the images be stored in video memory? If yes, I guess that just by using openGL huge (main) memory savings could be made.

What about games that are done by professionals? Some games have a lot of images, 3D models etc and they don't have memory problems (?). Are there techniques I should know?

Thanks





I strongly recommend you switching to OpenGL ES 1.0 or 2.0.

As for your last questions:
Your bitmaps are stored on the RAM, not the VRAM.

Your java code runs as compiled ByteCode on the Dalvik Virtual Machine.

1)Every object and variable is stored on the HEAP, which is the memory that the MOBILE has.

2)The only way you can store stuff on the VRAM, that would be by using the existing interface between the CPU an GPU, and that is by a library such as OpenGL ES.
OpenGL uses buffers which stores vertices information that can be used for several purposes (drawing), and since you are not using OpenGL, you won't ever touch the VRAM.

3)If you use OpenGL, you don't know how much memory you will save until you profile (test) your game on a certain real device.


4)About the professional games, the best answer I can give you right now is, that Images are stored in a PIXEL format on BUFFERS (Array of numbers) sent to OpenGL using a library, it is send as a texture, once that happens, you can delete any references to the recently created BITMAP, freeing memory from the CPU, and leaving the memory usage to the OpenGL GPU or CPU (don't focus on this right now, VBOs/FBOs).


5) OpenGL might seem hard at first, and it is, but you are smart enough to learn it ;).

Just watch some tutorials, and stick to Java.


1) Memory that the application has. Each Dalvik activity is reserved a set amount of memory for its heap.

2) Most mobile devices don't have dedicated VRAM - they have unified memory.

4) You appear to have thrown out a large number of unrelated terms. When loading a texture into OpenGL, you are passing a pointer to an array to the OpenGL library which is then stored internally, and you are given a handle to access the Texture Object. However, since most mobile devices have unified memory, VRAM == RAM. VBOs are unrelated and are related to storing vertex information.

#6 frob   Moderators   -  Reputation: 22693

Like
0Likes
Like

Posted 25 October 2012 - 02:09 PM

I'm also aware that png images consume width x height x 4 bytes when loaded into memory - but I guess I can't do anything about that.

Sure you can.

Simply put: Don't use PNG images for textures. Major games avoid it.

Move to compressed ETC1 format which should be supported by all GL2.0 devices. It is still RGB8, but much smaller than your uncompressed raw image. Some devices support additional compressed texture formats, like DXT1 and PVRTC, but you can always fall back to ETC1.

Check out my book, Game Development with Unity, aimed at beginners who want to build fun games fast.

Also check out my personal website at bryanwagstaff.com, where I write about assorted stuff.


#7 sheep19   Members   -  Reputation: 413

Like
0Likes
Like

Posted 25 October 2012 - 02:11 PM

Thanks - I will read some stuff about those you suggested 'cause it's the first time I hear about them.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS