Home > Tutorials > Image Processing – Invert Image On The Fly

Image Processing – Invert Image On The Fly


It’s so rare to find any tutorial or guide for image processing on Android, so I take some time to work over several things.

This next one is to invert color of an image.

Normal Image

Normal Image

After processing, it would be like:

Inverted Image

Inverted Image

How did I do that?

	public static Bitmap doInvert(Bitmap src) {
		// create new bitmap with the same settings as source bitmap
		Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
		// color info
		int A, R, G, B;
		int pixelColor;
		// image size
		int height = src.getHeight();
		int width = src.getWidth();

		// scan through every pixel
	    for (int y = 0; y < height; y++)
	    {
	        for (int x = 0; x < width; x++)
	        {
	        	// get one pixel
	            pixelColor = src.getPixel(x, y);
	            // saving alpha channel
	            A = Color.alpha(pixelColor);
	            // inverting byte for each R/G/B channel
	            R = 255 - Color.red(pixelColor);
	            G = 255 - Color.green(pixelColor);
	            B = 255 - Color.blue(pixelColor);
	            // set newly-inverted pixel to output image
	            bmOut.setPixel(x, y, Color.argb(A, R, G, B));
	        }
	    }

	    // return final bitmap
	    return bmOut;
	}

Every image pixel holds information of  four channels: Alpha, Red, Green, Blue; however, Alpha doesn’t reflect the image color as display. So I just keep its value, and take inversion for other three channels by formula: 0xFF – CurrentValue.

That’s all, very simple!

 

Hope you enjoy it!

 

Cheers,

Pete Houston

Categories: Tutorials Tags: , , ,
  1. voi
    August 9, 2016 at 2:54 pm

    do you provide any sample project ?

  2. September 5, 2014 at 7:34 pm

    its not handling orientation of camera and changing camera orientation with image capture as well thats wrong

  3. October 23, 2011 at 6:55 am

    Just wondered if you knew how heavy this is on the processor?
    I was thinking of using it to invert small icons when a user changes the theme in my application

  1. No trackbacks yet.

Leave a comment