Click here to Skip to main content
13,591,628 members
Click here to Skip to main content
Add your own
alternative version


12 bookmarked
Posted 17 Jan 2012
Licenced LGPL3

Silverlight Extended Canvas Control to Crop Images

, 19 Jan 2012
Rate this:
Please Sign up or sign in to vote.
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.

You may also be interested in...


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 
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
mvpSacha Barber17-Jan-12 4:51 
AnswerRe: I was going to write Pin
onatm17-Jan-12 5:26
memberonatm17-Jan-12 5:26 
GeneralRe: I was going to write Pin
Sacha Barber17-Jan-12 8:25
mvpSacha 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180618.1 | Last Updated 19 Jan 2012
Article Copyright 2012 by Onat Yiğit Mercan
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid