Rasmus Tolstrup Christensen

Black and white images with Xamarin

May 26, 2016 | 2 Minute Read

When you take a picture with the phones camera or choose one from the image gallery, how do you then make it black and white?

Pure Xamarin

This post is a general purpose of how to turn a picture from colored to black and white. It’s made with pure Xamarin, and if you want to use it in a Xamarin Forms project, just wrap is as a platform dependency, using DependencyService. This implementation will focus on the IOS version.

Let’s code

The code we’ll use is this one. Notice I wrapped it in a method with a parameter ot type byte[] which is the image to convert, and a return value of type _byte[] the black and white edition of the image.

public byte[] MakeGrayScale(byte[] imageAsBytes)
{
	UIImage image = ImageFromByteArray(imageAsBytes);
	var height = image.Size.Height;
	var width = image.Size.Width;
	var imageRect = new CGRect(0, 0, width, height);

	using (CGBitmapContext context = new CGBitmapContext(IntPtr.Zero,
											(int)width, (int)height, 8,
											0, CGColorSpace.CreateDeviceGray(),
											CGImageAlphaInfo.None))
	{
		context.DrawImage(imageRect, image.CGImage);

		UIKit.UIImage convertedImage = UIKit.UIImage.FromImage(context.ToImage(),
														 0, image.Orientation);

		return convertedImage.AsJPEG().ToArray();
	}
}

The concept is to make a new canvas of the same dimension as the original image, the context. When we define the context, we can also define a ColorSpace. Here we can choose CreateDeviceGray to make it black and white and we also remoce the Alpha. With the context and the rectangle in the same dimension as the original image, we can draw the new image on the canvas. Finally we need to create a new UIImage from the context and the orientation of the original image. We now have a copy of the original image, with a different ColorSpace.

The last step in the code snippet converts the image to JPEG and ensures we return it as byte[]

You can find the samle code as a gist here

comments powered by Disqus