Some time we need to crop an image uploaded by user in Silverlight or Windows Phone applications. Sometime we also need to do a rotate transform or skew transform to the image before saving it. So, how to achieve it?
This blog post will cover the code with details using the WriteableBitmap class that comes with the SDK. Continue reading to know more about it.
The WriteableBitmap class inherited from BitmapSource is present in the System.Windows.Media.Imaging namespace and provides the user a BitmapSource that can be written to and updated. Using this WriteableBitmap class, you can crop your images easily in your Silverlight or Windows Phone applications. Let’s write the code to implement the cropping functionality.
To crop an image, we will need an image source, the (x, y) co-ordinates of the image and the height & width of the cropped image. The API will crop the original image from the (x, y) co-ordinates to the dimension specified.
Here is the C# Code implementation:
Here is the VB.Net Code implementation:
The above code implementation will return you a cropped image based on the size specified. As it will return an WriteableBitmap instance, you can directly bind it to an image control or create image stream to save it in disk.
To know more about saving to an image stream, read this post: How to create Image Stream of XAML Page using Telerik’s ExportExtension method?
Now, we will need a XAML page to design our sample application where we will have two image controls and a button as shown below. You will be very easily able to create the XAML page and hence I am not sharing the whole code here.
The sample application consists of one large image (Original Image) at the left side and one small image (Cropped Image will show here) at the right side. Our implementation will be to crop a specified dimension of the original image and show it at the second image control on click of the button control.
To do this, first we will need to create a WriteableBitmap instance from the original image control and in case we need to do an transform operation on top of the image, we need to specify here, else we can put a “null” as the second parameter to it. Then call the CropImage() method with the required parameters to get the crop version of the original image as shown below.
Here is the C# version of the Code implementation:
Here is the VB.Net version of the Code implementation:
Now once you click the Crop button, you will notice that the second image at the right side has been changed with a cropped version of the image based on the size specified as the parameter to the CropImage() method. Here is the screenshot of the same:
I hope that, this post will help you to understand the use of WriteableBitmap and how to use this class to crop an image to specified dimension. If you have further queries on this, drop a line below and I will try to answer you as soon as I can.