Home > Tutorials > Image Processing – Pixel Color Replacement

Image Processing – Pixel Color Replacement


Some buddies has mailed me asking about replacing a pixel color by another.

For sample, of what I’ve done, this is how it looks.

Image - The Original

Image - The Original

The next one replaces all the 0xFFFFFFFF pixel into 0xFF0B0C0D color:

Image - The Replaced

Image - The Replaced

Not so beautiful, well, I’ve just picked random color….lol..

This is what I’ve done for it.

package pete.android.study;

import android.graphics.Bitmap;

public class ImageProcessor {
	Bitmap mImage;
	boolean mIsError = false;

	public ImageProcessor(final Bitmap image) {
		mImage = image.copy(image.getConfig(), image.isMutable());
		if(mImage == null) {
			mIsError = true;
		}
	}

	public boolean isError() {
		return mIsError;
	}

	public void setImage(final Bitmap image) {
		mImage = image.copy(image.getConfig(), image.isMutable());
		if(mImage == null) {
			mIsError = true;
		} else {
			mIsError = false;
		}
	}

	public Bitmap getImage() {
		if(mImage == null){
			return null;
		}
		return mImage.copy(mImage.getConfig(), mImage.isMutable());
	}

	public void free() {
		if(mImage != null && !mImage.isRecycled()) {
			mImage.recycle();
			mImage = null;
		}
	}

	public Bitmap replaceColor(int fromColor, int targetColor) {
		if(mImage == null) {
			return null;
		}

		int width = mImage.getWidth();
		int height = mImage.getHeight();
		int[] pixels = new int[width * height];
		mImage.getPixels(pixels, 0, width, 0, 0, width, height);

		for(int x = 0; x < pixels.length; ++x) {
			pixels[x] = (pixels[x] == fromColor) ? targetColor : pixels[x];
		}

		Bitmap newImage = Bitmap.createBitmap(width, height, mImage.getConfig());
		newImage.setPixels(pixels, 0, width, 0, 0, width, height);

		return newImage;
	}
}

Guess you already knew the basic concepts of image processing in all of my previous articles.
Hope you get something cool from it!

Cheers,
Pete Houston

Categories: Tutorials Tags: , , , ,
  1. April 2, 2013 at 11:06 pm

    can u plz tell about full coding

  2. pia
    December 28, 2012 at 1:32 pm

    Hi,
    Can u plz post the codes to produce effects like cross process,oilpaint,lomo,holga in an image….???

  3. jzab
    November 9, 2012 at 4:34 pm

    How did you call your image? I can’t find it in your .java code.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: