Archive

Posts Tagged ‘bitmap’

New Cache for Better Memory Performance


Hanging around and reading Android articles, and suddenly I want to check out new information on Android Training Page.

As a developer having lots of interest in Android Performance & Optimization, I check this section first: Cache with Bitmaps.

Got a note from the page:

Note: In the past, a popular memory cache implementation was a SoftReference or WeakReference bitmap cache, however this is not recommended. Starting from Android 2.3 (API Level 9) the garbage collector is more aggressive with collecting soft/weak references which makes them fairly ineffective. In addition, prior to Android 3.0 (API Level 11), the backing data of a bitmap was stored in native memory which is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash.

Just like something light up in my head, this explains why sometimes some of my apps crash in memory limitation strangely before.

The two new class introduced to work around with Bitmap Caching is: LruCache and DiskLruCache.

So if you got any problem with bitmap memory, this could be a hint to your optimizing solution for your Android apps.

 

Cheers,

Pete Houston

Categories: Tutorials Tags: , ,

Convert Bitmap to byte array and reverse

November 13, 2011 14 comments

If you want to convert a `Bitmap` to byte array:

public byte[] getByteArray(Bitmap bitmap) {
	ByteArrayOutputStream bos = new ByteArrayOutputStream();
	bitmap.compress(CompressFormat.PNG, 0, bos);
	return bos.toByteArray();
}

and if you want the reverse process:

public Bitmap getBitmap(byte[] bitmap) {
	return BitmapFactory.decodeByteArray(bitmap , 0, bitmap.length);
}

Cheers,
Pete Houston

Categories: Tricks & Tips Tags: , , ,

Image Processing – Tint Color (Yet Another)

October 18, 2011 6 comments

It’s been a long time since  I haven’t touched anything related to image processing. Well, today just got a new algorithm, which is pretty much nicer than the one I posted before.

Original Image

Original Image

A Tinted Image (50)

A Tinted Image (50)

Of course, this is how it’s done.

package pete.android.study.imageprocessing;

import android.graphics.Bitmap;

public class ImageProcessor {
	
	public static final double PI = 3.14159d;
	public static final double FULL_CIRCLE_DEGREE = 360d;
	public static final double HALF_CIRCLE_DEGREE = 180d;
	public static final double RANGE = 256d;
	
	public static Bitmap tintImage(Bitmap src, int degree) {

	    int width = src.getWidth();
		int height = src.getHeight();

	    int[] pix = new int[width * height];
	    src.getPixels(pix, 0, width, 0, 0, width, height);

	    int RY, GY, BY, RYY, GYY, BYY, R, G, B, Y;
	    double angle = (PI * (double)degree) / HALF_CIRCLE_DEGREE;
	   
	    int S = (int)(RANGE * Math.sin(angle));
	    int C = (int)(RANGE * Math.cos(angle));

	    for (int y = 0; y < height; y++)
	        for (int x = 0; x < width; x++) {
		    	int index = y * width + x;
		    	int r = ( pix[index] >> 16 ) & 0xff;
		    	int g = ( pix[index] >> 8 ) & 0xff;
		    	int b = pix[index] & 0xff;
		    	RY = ( 70 * r - 59 * g - 11 * b ) / 100;
		    	GY = (-30 * r + 41 * g - 11 * b ) / 100;
		    	BY = (-30 * r - 59 * g + 89 * b ) / 100;
		    	Y  = ( 30 * r + 59 * g + 11 * b ) / 100;
		    	RYY = ( S * BY + C * RY ) / 256;
		    	BYY = ( C * BY - S * RY ) / 256;
		    	GYY = (-51 * RYY - 19 * BYY ) / 100;
		    	R = Y + RYY;
		    	R = ( R < 0 ) ? 0 : (( R > 255 ) ? 255 : R );
		    	G = Y + GYY;
		    	G = ( G < 0 ) ? 0 : (( G > 255 ) ? 255 : G );
		    	B = Y + BYY;
		    	B = ( B < 0 ) ? 0 : (( B > 255 ) ? 255 : B );
		    	pix[index] = 0xff000000 | (R << 16) | (G << 8 ) | B;
	    	}
	    
	    Bitmap outBitmap = Bitmap.createBitmap(width, height, src.getConfig());	   
	    outBitmap.setPixels(pix, 0, width, 0, 0, width, height);
	   
	    pix = null;
	   
	    return outBitmap;
	}
}

This is a quite complicated algorithm, yet I don’t really understand it clearly.
I’ve found it at this link Developer.Com – Working with images in Google Android

Another tinted one, nice one:

Nice Tinted Image

Nice Tinted Image

Have fun with it!

Cheers,

Pete Houston

Categories: Tutorials Tags: , , , , ,

Store and use files in Assets

October 2, 2011 32 comments

There are times when you probably want to your application distribution with raw resources, instead of pre-defined resources, the ‘res‘ folder, you gonna have to make use of ‘Asset‘.

Assets’ folder will be distributed along with the APK, which contains all the raw files you need for application, such as: text files (.txt), non-Android XML files (.xml), Audio files (.wav, .mp3, .mid)…; those cannot be put into ‘res‘ folder as usual.

Thing needed to be looked up here: AssetManager from Android Developers’ References

This class does the job that we need.

First, create a project as usual, then put files into ‘asset‘ like below:

Files in 'Assets'

Files in 'Assets'

Now, create a simple layout containing a TextView for displaying the content of ‘text.txt‘ and an ImageView for displaying the image ‘avatar.jpg’, which are put in Asset.

The implementation quite easy using AssetManager as mentioned above.

package pete.android.study;

import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class Main extends Activity {

	ImageView mImage;
	TextView mText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mImage = (ImageView)findViewById(R.id.image);
        mText = (TextView)findViewById(R.id.text);
        loadDataFromAsset();
    }

    public void loadDataFromAsset() {
    	// load text
    	try {
    		// get input stream for text
	    	InputStream is = getAssets().open("text.txt");
	    	// check size
	    	int size = is.available();
	    	// create buffer for IO
	    	byte[] buffer = new byte[size];
	    	// get data to buffer
	    	is.read(buffer);
	    	// close stream
	    	is.close();
	    	// set result to TextView
	    	mText.setText(new String(buffer));
    	}
    	catch (IOException ex) {
    		return;
    	}

    	// load image
    	try {
	    	// get input stream
	    	InputStream ims = getAssets().open("avatar.jpg");
	    	// load image as Drawable
	    	Drawable d = Drawable.createFromStream(ims, null);
	    	// set image to ImageView
	    	mImage.setImageDrawable(d);
    	}
    	catch(IOException ex) {
    		return;
    	}

    }
}

That’s a quick sample code giving this result.

Read data from Asset

Read data from Asset

The distributed APK file contains the folder ‘assets‘, you might wanna check by opening it.

Quite easy, isn’t it?

@p/s: you can load image from Asset into Bitmap by using BitmapFactory.decodeStream(), instead of using Drawable.

Have fun w/ Android Coding 🙂

 

Cheers,

Pete Houston

Categories: Tutorials Tags: , , , , , ,

Copy Bitmap object to avoid references

September 10, 2011 2 comments

If you assign value of a Bitmap to the other one, it means you have create a reference to the source Bitmap. Hence, if either one is recycled, the other one certainly reference to the already-recycled Bitmap object in memory, which might cause some problems like: Exception on Bitmap, throwIfRecycled.

In some case, you probably want to copy a Bitmap object to a new one, here the trick:

Bitmap src = .....<allocated the source Bitmap>
Bitmap newBitmap = src.copy(src.getConfig(), src.isMutable() ? true : false);

Pretty much simple!
@Remember to recycle each one after used.

Cheers,
Pete Houston

Bitmap and memory leak! – Part 2

September 10, 2011 3 comments

One of the common mistakes developers often make is that never take care of Bitmap object stored in a data structure like List, LinkedList, HashMap

Here a sample:

public class BitmapStorage {
	String mContent;
	ArrayList<Bitmap> mImages;

	// constructor to create the objects
	public BitmapStorage(String content, ArrayList<Bitmap> images) {
		mContent = content;
		mImages = images; // references
	}
}

Things seem to be fined IF developers try to release memory of this BitmapStorage object somewhere else. WHAT IF they FORGET? It’s gonna be really a mess, isn’t it?

In my opinion, it is much better if providing such a way to handle memory in such a class.

package pete.android.study;

import java.util.ArrayList;

import android.graphics.Bitmap;

public class BitmapStorage {
	String mContent;
	ArrayList<Bitmap> mImages;

	// constructor to create the objects
	public BitmapStorage(String content, ArrayList<Bitmap> images) {
		mContent = content;
		mImages = images; // references
	}

	// call in order to free memory of Bitmap objects
	public void freeBitmaps() {
		for(Bitmap image: mImages) {
			// also, it's better to check whether it is recycled or not
			if(image != null && !image.isRecycled()) {
				image.recycle();
				image = null; // null reference
			}
		}
	}

	// the destructor should also handle the memory in case it still holds memory
	protected void finalize() {
		freeBitmaps();
	}
}

Like this, developers can freely choose to release memory whenever they feel done with the BitmapStorage objects and when they forget to do so, the destructor “finalize()” would handle the rest.

@Just a note, make sure your Bitmap objects don’t link to any other things when recycling; it would be troublesome. Try to create a nice Bitmap objects live well in a life-cycle!

 

Cheers,
Pete Houston

Categories: Tutorials Tags: , , , ,

Bitmap and memory leak!

September 7, 2011 1 comment

Whenever using a Bitmap object, it consumes the heap memory! So if your code simply just declares and use it without release its memory, you would face memory leak problem.

It’s men

Remember to always free Bitmap objects memory before finishing your application or whatever objects containers.


Bitmap image = ..... (whatever)

...

if(image != null) {

image.recycle();

image = null;

}

It’s mentioned here on Android Documentation References: Bitmap.recycle()

 

Cheers,

Pete Houston

Categories: Tutorials Tags: , , , ,