.NET Zone is brought to you in partnership with:

Den is a DZone Zone Leader and has posted 460 posts at DZone. You can read more from them at their website. View Full User Profile

Image Cropping In Windows 8 Metro Applications

05.12.2012
| 7526 views |
  • submit to reddit

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.FileTypeFilter.Add(".bmp");
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();
image.SetSource(inputStream);

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.