Skip to content Skip to sidebar Skip to footer

Reducing Memory Usage While Creating And Saving A Single Color Png Bitmap In Android

I need to create and save single color PNG images (bitmap filled with a single color). I'm creating the bitmap: public static Bitmap createColorSwatchBitmap(int width, int height,

Solution 1:

You can use the PNGJ library (disclaimer: I'm the author). Because it saves the image progressively, it only needs to allocate a single row.

For example:

publicstaticvoidcreate(OutputStream os,int cols,int rows,int r,int  g,int  b,int  a)  {     
        ImageInfoimi=newImageInfo(cols, rows, 8, true); // 8 bits per channel, alphaPngWriterpng=newPngWriter(os, imi);
        // just a hint to the coder to optimize compression+speed:
        png.setFilterType(FilterType.FILTER_NONE); 
        ImageLineByteiline=newImageLineByte (imi);
        byte[] scanline = iline.getScanlineByte();// RGBAfor (intcol=0,pos=0; col < imi.cols; col++) { 
           scanline[pos++]=(byte) r;  
           scanline[pos++]=(byte) g;
           scanline[pos++]=(byte) b;
           scanline[pos++]=(byte) a;
        }
        for (introw=0; row < png.imgInfo.rows; row++) {
           png.writeRow(iline);
        }
        png.end();   
 }

It seems so overkill to allocate almost 6 MB of memory for a file that will only have 8 KB.

There are two different things here. First, the space wasted in order to allocate the full image in memory - my solution alliviates this, by allocating a single row. But, apart from this, you are making a conceptual error: it make no sense to compare the space allocated in memory with the encoded image size, because PNG is a compressed format (and a single color image will be highly compressed). The memory allocated by any raw editable bitmap (Bitmap in Android, BufferedImage in ImageIO, my own ImageLineByte in PNGJ, or whatever) in practice will never be compressed, and hence it will always waste 4 bytes per pixel - at least. And you can check that: 1200x1200x4=5760000.

Solution 2:

You just fill bitmap with only one single color. Why don't you just store colors in SharedPreferences?

It will be much more efficient.

Although, you can just set color background for Views.

Other option is create bitmap of size 1x1 pixel with necessary color and set is as background. It will become size of View.

P.S.

ALPHA_8 don't store color, only alpha. It's completely wrong, check documentation

Post a Comment for "Reducing Memory Usage While Creating And Saving A Single Color Png Bitmap In Android"