Previously I’ve written about how to access image pixel data in a C++/CX Windows Store App. Depending on your app, you may have a requirement to perform imaging operations that manipulate the pixel values of an image. Rather than have an Image control display a BitmapImage, I’ve modified my PhotoViewer sample app to display a WriteableBitmap instead, allowing the manipulation of an image at the pixel level. This should be a useful blog post as many of the posts concerning this topic on the forums are not optimal.
In the sample app, when the PhotoPage is loaded, the OnNavigatedTo method is called, which in turn calls the LoadPhoto method.
This method simply loads the photo from disk, and decodes it for display in a WriteableBitmap. The pixel data in a WriteableBitmap is stored in the PixelBuffer property. However, this property is read-only. In managed languages, you can use the AsStream extension method (from the System.Runtime.InteropServices.WindowsRuntime namespace) to access the underlying buffer as a stream. To see how to access the underlying buffer in C++/CX, see this blog post.
The code above accesses the underlying buffer in the WriteableBitmap as a stream, creates a new byte array to store the pixel data, and then reads the pixel data from the stream to the byte array. Then the ToGreyscale method is called to convert the pixel data to greyscale.
The ToGreyscale method iterates through the srcPixel byte array, converting each value to its equivalent greyscale representation, before returning it to the calling method. Note that the pixel data is stored in BGRA format.
Back in the calling method the stream that accessed the underlying buffer in the WriteableBitmap has its position reset to the beginning. Then the destPixels byte array, containing the greyscale representation of the image data, is written back to the stream, and hence to the underlying WriteableBitmap. A call is made to the WriteableBitmap.Invalidate method to request a redraw of the entire bitmap.
The pixel data in a WriteableBitmap is stored in the PixelBuffer property. However, this property is read-only. In managed languages, you can use the AsStream extension method (from the System.Runtime.InteropServices.WindowsRuntime namespace) to access the underlying buffer as a stream. You can then use the Read and Write methods on the stream to access the pixel data and replace it.
The sample app can be downloaded here.