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.

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[]