Memory issues drawing 5 small images - android

My app is using way too much memory, and I'm not too sure why. I'm making a solitaire game. I'm using a chained ConstraintLayout of 10 equal width RelativeLayouts (1 for each stack of cards). [I know I can use other Viewgroups].
My app is using ~15mb memory, until I do this;
public void DrawCardsMat0()
{
RelativeLayout mat = (RelativeLayout) findViewById(R.id.PLAY_Mat0);
mat.removeAllViews();
RelativeLayout rl = new RelativeLayout(this);
for (PlayingCard playingCard : Stack0.Cards)
{
ImageView myImg = GetCardImage(playingCard);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(CardWidth, CardHeight);
lay.setMargins(0, playingCard.UI_MarginTop, 0, 0);
mat.addView(myImg, lay);
}
}
and
public ImageView GetCardImage(PlayingCard playingCard)
{
ImageView myImg = new ImageView(this);
// a simple switch is used to here to pick the drawable. Removed as there's 52 cards)
myImg.setImageResource(R.drawable.s1);
return myImg;
}
CardWidth and CardHeight are ints (150 and 210, roughly. Pixels).
This draws FIVE cards, and each .jpg is ~60KB (yes, KB). This results in 60MB of memory usage. 10 cols == 600mb of memory (I assume, as it's OOM before then).
The images are in a RelativeLayout, and are placed on top of each other. MarginTop is used to "stack" them.
thanks in advance
--- update 1 ---
I'm now using a 46KB bmp image.
Creating 5 ImageViews (one stack's worth) in XML (and don't call anything in code) uses ~50mb memory. Tested using a LinearLayout.
Creating same images in-code uses same amount of memory.
--- update 2 ---
If I create a new Activity, with just a simple LinearLayout and 5 ImageViews, and no java code, it still uses ~50MB memory.

When working with bitmaps, you should always be careful. I'll describe the most important points and considering them, you can change the way work with card images is organized.
Bitmap in memory always exists in uncompressed format, so its size will be different from the size of your .jpg/.png/.webp/.[whatever compressed format]. The actual size depends on the Bitmap.Config, but by default Android will use ARGB_8888 (1 byte for alpha channel, 1 byte for each of R/G/B channels). You can roughly estimate the size in memory by saving the image in .bmp format.
When you use <bitmap> tag with drawable, it means in runtime bitmap will be wrapped in BitmapDrawable. As you can see, by default bitmap will be loaded as-is, taking original size.
When you call myImg.setImageResource(R.drawable.s1) it means that bitmap will have the same size as before in memory, it will be just scaled by using the matrix depending on the size of ImageView and scaleType you specified.
Considering that, probably you may want to load downscaled bitmap to the memory, depending on the view size. You can do that by using BitmapFactory class instead. I suggest you to read these 2 articles in order to understand how Android is working with bitmaps: Managing Bitmap Memory and Loading Large Bitmaps Efficiently.
You may also consider using some image library, like Picasso or Glide which can load downscaled bitmap depending on the size of ImageView. You can also try to use Fresco which keeps bitmap outside of JVM heap.
If you have such possibility, better to have cards in SVG format. Then you can work with vectors instead of having bitmap, which is much more memory-friendly (because SVG is just a set of instructions on how to draw). However in case of really complex SVG file you can hit another problem - it will take a lot of time to draw it. Check this article on how to use it with ImageView.

Related

Android Memory Leak - setBackgroundDrawable - with images

When a user clicks a button, i keep switching the background of a layout like this in Activity code:
...
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img1));//On First click
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img2));//On Second Click
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img10));//On 10th Click
...
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img1));//On 11th Click 1st image again and so on.
I have 10 images which i keep rotating.
Soon, it causes OutOfMemory exception. What am i doing wrong?
If it matters in my manifest file i have:
android:minSdkVersion="11"
android:targetSdkVersion="17" />
EDIT 1
Average size of the image is: 50K
Average dimension of the image is: 600x450
All images img1, img2 etc.. are jpeg images
Solution Update
Reducing image dimensions to 300x200 resolved the issue. The memory requirements went down significantly by this single change.
It might be happening because your image resources are in drawable folder; which is equivalent to drawable-mdpi. And your device might be something other than mdpi.
So, either provide images for all the screed densities you are gonna support. Or, put images in drawable-nodpi, so your images will not be resized. Hence no OutOfMemoryException.
Referred from here
Use Bitmap.recycle() if you can change your Drawable with Bitmap.
Hope This will help
Each bitmap with dimension 600x450 has size of 600*450*4 = 1 080 000 bytes (1 MB) in RAM.
You should load so large bitmaps in another way:
Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.img1);
myLayout.setBackgroundDrawable(new BitmapDrawable(resources, bitmap));
And before changing background of the view you have to do
Drawable background = myLayout.getBackground();
if (background != null && background instanceof BitmapDrawable) {
myLayout.setBackgroundDrawable(null);
BitmapDrawable bd = (BitmapDrawable) background;
bd.getBitmap().recycle();
}
I dont think changing background layout so frequently is a good idead. I suggest that you could use RelativeLayout with an ImageView as first item. Then everytime you need to change your background, you can change your ImageView with some cached library such as: Universal Image Loader

Scaled images with volley

I am trying to stretch images that I load with volley. XML isn't much help, while it can shrink them it doesn't help enlarging them. My exploration of the topic led me to the conclusion that this can be achieved only programmatically.
What is my idea ?
To extend the volley library and overriding one of the methods, resizing the bitmap right after download and before displaying it.
I used this code to resize images that were already on the phone, but this doesn't help me much with random images from the internet.
Point outSize=new Point();
float destWidth=1;
float destHeight=1;
#SuppressWarnings("deprecation")
#TargetApi(13)
private Bitmap scaleBitmap(int mFile){
Display display = getActivity().getWindowManager().getDefaultDisplay();
if (android.os.Build.VERSION.SDK_INT >= 13){
display.getSize(outSize);
destWidth = outSize.x;
destHeight = outSize.y;
}else{
destWidth=display.getWidth();
destWidth=display.getHeight();
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap orig = BitmapFactory.decodeResource(getResources(), mFile);
float srcWidth = orig.getWidth();
float srcHeight = orig.getHeight();
float inSampleSize = 1;
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
inSampleSize=(destHeight/2)/srcHeight;
}else{
inSampleSize=(destHeight/4)/srcHeight;}
options = new BitmapFactory.Options();
Bitmap resized=Bitmap.createScaledBitmap(orig, (int)Math.round(orig.getWidth()*inSampleSize), (int)Math.round(orig.getHeight()*inSampleSize), true);
destWidth=1;
destHeight=1;
return resized;
}
Basically I want to assign to orig the image that is downloaded, then resize it and then display it.
My question is: What class do I extend ? I took a look there but since I am inexperienced I couldn't figure out what exactly to look for. Is it ImageLoader ? And more specifically: should i Override the getBitmap() method and add an edited version of the code for scaling ?
Disclaimer: I am very inexperienced and I would accept other ideas too.
I solved it a few days ago. Here is how the regular ImageView handles resizing of images: If you are using Match_parent as width and wrap_content as height(I tested with both as match_parent and the results were the same) it will NOT scale the image IF the Height of your picture is lower than the width (which is quite typical) . Meaning that image view scales based on the smaller side. This meant that there are 2 solutions:
Do what I wanted to do originally which involves writing a new class that extends imageview/networkimageview and then programmatically adding the code that i listed to enlarge the picture.
Or simply specify the desired Height of the view programmatically and imageview will then simply scale the image to fit the height of the new View. This options invalidates the wrap_content for Width and simply puts in as much as you need.
Here is the code I used:
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point outSize=new Point();
int destWidth;
if (android.os.Build.VERSION.SDK_INT >= 13){
display.getSize(outSize);
destWidth = outSize.x;
}else{
destWidth=display.getWidth();
}
img.setLayoutParams(new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT,destWidth*5625/10000));
In my case I needed to fit a 640x360 image so I used a ratio of 0,5625. This method will work if you do not know the picture's parameters BUT you have to get the parameters beforehand and put them in place, so I guess it might be more useful to use the first strategy, but since I solved my problem I don't have an example for the first method.
I think the issue that you're seeing is caused by the default behavior of how the underlying code for NetworkImageView works.
Have a look at the code for ImageRequest which is used by NetworkImageView . There is a function there called getResizedDimension which says something like "Scales one side of a rectangle to fit aspect ratio" . This may have caused your issue since the image(s) that you're downloading may not have the perfect aspect ratio computed every time for a specific device.
Are you displaying a single image, or images in a grid? If it is just a single image, there might be a work around. I haven't seen your full code, on where you set the image or image url, so I am going to assume the flow here:
1.) Use the regular ImageView.
2.) Use the regular Volley request pointing to the image's URL
3.) When you receive the response (parseNetworkResponse), decode (the array of bytes) it yourself, using the method you mentioned above that works for you. Some tips can also be found here on how to do that: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
4.) After decoding, programmatically set the ImageView's bitmap with your decoded result
If this is a grid type thing, then maybe you need to make your own version of NetworkImageView and its underlying support classes (sub-class).
Suggestion:
Have a look at Picasso as well, IF you have the freedom to choose the library. Looks very simple to use for your stated needs.

android background image slows down app

I am using a viewpager to swipe amongst fragments in my app. I define the background in the XML, so
android:background="#drawable/bg_final"
If I use a simple background color, my app works very smooth. If I use it with this background image, fps decreases and my app becomes only passable. It is not slow, just not so smooth, however on weaker devices it could work laggy. Is it a bad way to apply a background image? The whole image is a 480x800 png with the size of 14.7kB. What might be the problem?
(the backgrounds of the fragments are transparent, the viewpager is in a main.xml which has its background with this image)
There are lots of answers out there that point to pre-scaling your bitmap. This is very imporant and you should do it if you can, however after trying several different things, the biggest performance gain I experienced was to create a view and override the onDraw method.
The class could be as simple as this:
public class DTImageView extends View {
public Bitmap imageBitmap;
public DTImageView(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(imageBitmap != null)
canvas.drawBitmap(imageBitmap, 0, 0, null);
}
}
Invoke the code using a prescaled bitmap:
DTImageView bgImageView = new DTImageView(context);
bgImageView.imageBitmap = Bitmap.createScaledBitmap(bitmap,width,height,true);
At this point you can add this view to the view hierarchy where it belongs. In my case, my view hierarchy had a bgImage, a middle ground where all the other functionality happened, and fgImage.
Use the android sdk tool Hierarchy Viewer to profile the app and see how fast each view is taking to draw. My app spent 30-40ms drawing the bgImage and fgImage. Pre-scaling and overriding onDraw reduced that 30-40ms to about 1.5ms.
Here is a screenshot of the Draw performance for one of my views before and after:
BEFORE:
AFTER:
I'm a bit late, but this just bit me, and when running the GPU debugger, I noticed that the system scaled up my image! I had a 1920x1080 image, and it showed up as a 3780x6720 texture!
Ideally, you should have textures for each density in the respective folder (res/drawable-mdpi, res/drawable-hdpi, etc).
However, if you think your one texture is fine, put it into res/drawable-nodpi, not res/drawable. If you put it into res/drawable-nodpi, the system won't scale it up based on the dpi.
In my case, it changed a simple UI from 10fps on a Pixel XL to the full frame rate of 60fps.
I had a background image, not big in size, but with weird dimensions - therefore the stretching and bad performance. I made a method with parameters Context, a View and a drawable ID(int) that will match the device screen size. Use this in e.g a Fragments onCreateView to set the background.
public void setBackground(Context context, View view, int drawableId){
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawableId);
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), bitmap);
view.setBackground(bitmapDrawable);
}
The reason for this could be that the image is being stretched, and Android has performance issues with stretching background images.
Instead, you should either replace the background image with either a background color or see this answer to have the image repeat instead of stretch.
I had the same problem and I resolved it by using this method:
Add your image to the mipmap folder which is located under the res directory. It will add the image according to it's density.
Create add only one background image with size 1080x1920 and put it in drawable-nodpi folder and that solved this problem

Android OutOfMemoryError while using multiple images

In my application, i have 3 screens containing multiple high resolution images. The number of images used in a screen is around 70-75. I have written the code to add images in a grid layout using an adapter class extending BaseAdapter, in the getView() method i wrote the code,
adapter = new ImageAdapter(this);
gridview.setAdapter(adapter);
int x = (int)(width/5.1f);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(x,x));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 20, 4, 20);
but while loading this screen, it show lots of memory issues, and in logcat i am getting the error,
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
Please share how could i write the code to handle memory issues with multiple high resolution images. Thanks.
If there is no way to adjust the images resolutions you should open them as BitmapFactory.Options().inJustDecodeBounds = true, pass your options to the images (desired adjusted size) and then decode them again using BitmapFactory.Options().inJustDecodeBounds = false.
The actual byte size of a bitmap image is calculated by multiplying the number of pixels by then number of bytes allocated for the pixel. ARGB_8888 (which is recommended) allocates 4 bytes per pixel, therefore, the size will be width * height * 4 Bytes.
For more details read the Loading Large Bitmaps Efficiently lesson from Android. Also this post should help.

ImageView: automatically recycle bitmap if ImageView is not visible (within ScrollView)

So, I've been looking at the ImageView source for a while, but I haven't figured out a hook to do this yet.
The problem: having, let's say, 30 400x800 images inside a ScrollView (the number of images is variable). Since they fit exactly in the screen they will take 1.3 MB of RAM each.
What I want: to be able to load/unload bitmaps for the ImageViews that are currently visible inside a ScrollView. If the user scrolls and the bitmap is no longer visible (within a distance threshold) the bitmap should be recycled so that the memory can be used by other bitmaps in the same ScrollView. I'm doing downsampling and all that, so no worries there. Bonus points if you do this by only extending ImageView (I would like to not mess with the ScrollView if possible).
Summary: I can make the images load only after the ImageView becomes visible (using a clever trick), but I don't know when to unload them.
Notes: I can't do this with a ListView due to other usability reasons.
Call this method when you want to recycle your bitmaps.
public static void recycleImagesFromView(View view) {
if(view instanceof ImageView)
{
Drawable drawable = ((ImageView)view).getDrawable();
if(drawable instanceof BitmapDrawable)
{
BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable;
bitmapDrawable.getBitmap().recycle();
}
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
recycleImagesFromView(((ViewGroup) view).getChildAt(i));
}
}
}
Have a look at the android documentation about "How to draw bitmaps" Also the code example called bitmap fun.
If you use a ListView or a GridView the ImageView objects are getting recycled and the actual bitmap gets released to be cleaned up by the GC.
You also want to resize the original images to the screen size and cache them on disk and/or RAM. This will safe you a lot of space and the actual size should get down to a couple of hundert KB. You can also try to display the images in half the resolution of your display. The result should still be good while using much less RAM.
What you really want is to use an ArrayAdapter for this. If, like your notes suggest, that is not possible (although i don't see why) take a look at the source for array adapter and rewrite one to your own needs.

Categories

Resources