Click here to Skip to main content
15,313,293 members
Articles / Programming Languages / C#
Posted 17 Jan 2012


12 bookmarked

Silverlight Extended Canvas Control to Crop Images

Rate me:
Please Sign up or sign in to vote.
3.36/5 (6 votes)
19 Jan 2012LGPL31 min read
Silverlight Extended Canvas Control to Crop Images
Image cropping in action


CanvasExt is a part of the project Onym Silverlight Toolkit.


I was working on a SharePoint Web Part project which is about image manipulation. As my default behaviour, I searched the whole of CodeProject to find out any solution. However, there was only one which is provided by Sacha Barber and it only aims at WPF. As he stated on his WPF Interactive Image Cropping Control article, his work needs to be ported to Silverlight.

Long story short, this article is about extending Silverlight's Canvas control to crop images.

How It Works

Basically, Canvas is subclassed and its mouse events are overridden to achieve live action image cropping. Every time user makes mouse actions on CanvasExt, either a new Rectangle is added or resized, using the mouse coordinates on the control. User can also move the Rectangle.

CanvasExt is shown below:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace onym.silverlight.toolkit
    public class CanvasExt : Canvas
        private bool _isImageLoaded;
        private bool _isCanvasMouseCaptured;
        private bool _isRectSelectorMouseCaptured;
        private Image _imgCroppable;
        private Point _pntMoveStart;
        private Point _pntRectSelector;
        private Point _pntSelection;
        private Shape _rectSelector;
        //private Style _rectSelectorStyle;

        public CanvasExt()
            MouseLeftButtonDown += canvasExt_MouseLeftButtonDown;
            MouseLeftButtonUp += canvasExt_MouseLeftButtonUp;
            MouseMove += canvasExt_MouseMove;
            _isImageLoaded = false;
            _isCanvasMouseCaptured = false;

        public void LoadFromBitmapImage(BitmapImage bmpCroppable)
            if (_isImageLoaded)
                _imgCroppable = null;
            _imgCroppable = new Image {Source = bmpCroppable, 
            VerticalAlignment = VerticalAlignment.Top};
            _imgCroppable.MouseLeftButtonDown += canvasExt_MouseLeftButtonDown;
            _isImageLoaded = true;
            Width = bmpCroppable.PixelWidth;
            Height = bmpCroppable.PixelHeight;

        public WriteableBitmap CropImage()
                WriteableBitmap wbSource = new WriteableBitmap(_imgCroppable, null);

                int sourceWidth = wbSource.PixelWidth;
                int w = (int) _rectSelector.Width;
                int h = (int) _rectSelector.Height;
                WriteableBitmap wbResult = new WriteableBitmap(w, h);

                for (int y = 0; y <= h - 1; y++)
                    int sourceIndex = (int) GetLeft(_rectSelector) + 
            ((int) GetTop(_rectSelector) + y)*sourceWidth;
                    int destinationIndex = y*w;
                    Array.Copy(wbSource.Pixels, sourceIndex, 
            wbResult.Pixels, destinationIndex, w);

                _rectSelector = null;
                return wbResult;
            catch(Exception ex)
                return null;

        private void canvasExt_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            if (_isRectSelectorMouseCaptured) return;
            if (!_isCanvasMouseCaptured && _isImageLoaded)
                _rectSelector = null;
                _pntSelection = e.GetPosition(this);
                _isCanvasMouseCaptured = true;

        private void canvasExt_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            _isCanvasMouseCaptured = false;

        private void canvasExt_MouseMove(object sender, MouseEventArgs e)
            if (!_isCanvasMouseCaptured) return;
            if (_rectSelector == null)
                //if (_rectSelectorStyle != null)
                //    rectSelector.Style = _rectSelectorStyle;
                _rectSelector = new Rectangle
                                    Stroke = new SolidColorBrush(Colors.LightGray),
                                    Fill = new SolidColorBrush(Colors.Yellow),
                                    Opacity = 0.20,
                                    Cursor = Cursors.Hand
                _rectSelector.MouseLeftButtonDown += rectSelector_MouseLeftButtonDown;
                _rectSelector.MouseLeftButtonUp += rectSelector_MouseLeftButtonUp;
                _rectSelector.MouseMove += rectSelector_MouseMove;
                SetZIndex(_rectSelector, 100);

            if (e.GetPosition(this).X <= Width && e.GetPosition(this).X > 0)
                double width = Math.Abs(_pntSelection.X - e.GetPosition(this).X);
                double left = Math.Min(_pntSelection.X, e.GetPosition(this).X);

                _rectSelector.Width = width;
                SetLeft(_rectSelector, left);

            if (e.GetPosition(this).Y <= Height && e.GetPosition(this).Y > 0)
                double height = Math.Abs(_pntSelection.Y - e.GetPosition(this).Y);
                double top = Math.Min(_pntSelection.Y, e.GetPosition(this).Y);

                _rectSelector.Height = height;
                SetTop(_rectSelector, top);

        private void rectSelector_MouseLeftButtonDown
            (object sender, MouseButtonEventArgs e)
            if (_isRectSelectorMouseCaptured) return;
            _pntMoveStart = e.GetPosition(this);
            _pntRectSelector.X = GetLeft(_rectSelector);
            _pntRectSelector.Y = GetTop(_rectSelector);
            _isRectSelectorMouseCaptured = true;

        private void rectSelector_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            _isRectSelectorMouseCaptured = false;

        private void rectSelector_MouseMove(object sender, MouseEventArgs e)
            if (!_isRectSelectorMouseCaptured) return;
            double left = _pntMoveStart.X - e.GetPosition(this).X;

            if (_pntRectSelector.X + _rectSelector.Width - left <= Width &&
                _pntRectSelector.X - left > 0)
                SetLeft(_rectSelector, _pntRectSelector.X - left);

            double top = _pntMoveStart.Y - e.GetPosition(this).Y;

            if (_pntRectSelector.Y + _rectSelector.Height - top <= Height &&
                _pntRectSelector.Y - top > 0)
                SetTop(_rectSelector, _pntRectSelector.Y - top);

How To Use It

Simply place a CanvasExt control to your XAML:

<onym:CanvasExt x:Name="canvasExtTest" />

Load the image into CanvasExt:

BitmapImage bmp = new BitmapImage();
FileStream fs = imgOpenFileDialog.File.OpenRead();

And crop the image:

imgCropped.Source = canvasExtTest.CropImage();

Final Words

It was a really quick and fun project to learn the basics of Silverlight but also painful: BitmapImage does not work with .bmp images and it took many hours to figure out that the problem was not in my code.


  • v0.1.1 - 18/01/12: Code refactored release
  • v0.1 - 24/12/11: First release


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


About the Author

Onat Yiğit Mercan
Software Developer (Junior)
Turkey Turkey
Geomatics Engineer.

MSC Computational Science and Engineering.

Comments and Discussions

GeneralMy vote of 2 Pin
Kashif_Imran20-Jul-13 22:48
MemberKashif_Imran20-Jul-13 22:48 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan24-Aug-13 10:59
MemberOnat Yiğit Mercan24-Aug-13 10:59 
GeneralRe: My vote of 2 Pin
Kashif_Imran24-Aug-13 11:09
MemberKashif_Imran24-Aug-13 11:09 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan24-Aug-13 11:26
MemberOnat Yiğit Mercan24-Aug-13 11:26 
Questionmouse events for _rectSelector is not necessary Pin
quyun28-Jul-12 15:47
Memberquyun28-Jul-12 15:47 
QuestionMy cropper Pin
darrellp26-Jan-12 20:12
Memberdarrellp26-Jan-12 20:12 
I'm not sure why your search didn't turn up my old cropper here:

A Photoshop-like Cropping Adorner for WPF[^]

The main advantages are that it doesn't write to a file on disk, works with arbitrary controls and obscures the part to be cropped rather than the part to be saved ala Photoshop (which makes much more sense I think - you want to obscure the part you're going to throw away - not the part you want to keep).
AnswerRe: My cropper Pin
Onat Yiğit Mercan27-Jan-12 10:16
MemberOnat Yiğit Mercan27-Jan-12 10:16 
GeneralMy vote of 2 Pin
Georgi Atanasov17-Jan-12 11:03
MemberGeorgi Atanasov17-Jan-12 11:03 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan17-Jan-12 11:18
MemberOnat Yiğit Mercan17-Jan-12 11:18 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan20-Jan-12 9:06
MemberOnat Yiğit Mercan20-Jan-12 9:06 
QuestionI was going to write Pin
Sacha Barber17-Jan-12 4:51
MemberSacha Barber17-Jan-12 4:51 
AnswerRe: I was going to write Pin
Onat Yiğit Mercan17-Jan-12 5:26
MemberOnat Yiğit Mercan17-Jan-12 5:26 
GeneralRe: I was going to write Pin
Sacha Barber17-Jan-12 8:25
MemberSacha Barber17-Jan-12 8:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.