Over a million developers have joined DZone.

Image Cropping In Windows 8 Metro Applications


Among other API changed in WinRT, major changes were introduced to the image manipulation capabilities available in the .NET Framework out-of-the-box. For one of my projects - a tile editor, I needed to uniformly crop an image given specific pre-defined conditions. In WPF there was CroppedBitmap that allowed me to do that. In WinRT this class is no longer available. I was considering relying on low-level APIs when I realized that there is, in fact, one managed workaround, that might be acceptable in specific cases.

Here is the situation - you are loading am image from a local (or remote) file:

var filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

var file = await filePicker.PickSingleFileAsync();

var inputStream = await file.OpenAsync(FileAccessMode.Read);

To get an actual working image, you might use the BitmapImage class:

BitmapImage image = new BitmapImage();

Here is the catch. From here you will need to work with an Image control and rely on its properties and workings. One of them - the image scale. By default, the Image control will scale your image to the height of the container, and that might cause cropping problems, since you will be selecting the scaled area instead of the sector that is actually needed. There are two ways to avoid it:

1. Set the Stretch property for the Image control to None - that way, the image will not be stretched.

imgTest.Source = image;
imgTest.Stretch = Stretch.None;

2. Use a BitmapDecoder to get the proper size of the image and resize the Image control.

BitmapDecoder decoder = await BitmapDecoder.CreateAsync(inputStream);
imgTest.Source = image;
imgTest.Height = decoder.PixelHeight;
imgTest.Width = decoder.PixelWidth;

Once this is completed, it is possible to call the Clip method to get the region that should be extracted:

imgTest.Clip = new RectangleGeometry() { Rect = new Rect(0, 0, 64, 48) };

Congratulations. You can now use WriteableBitmap to either capture the region or keep the image clipped as it is.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}