Click here to Skip to main content
15,867,999 members
Articles / Programming Languages / C#

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 30.3K   688   12   13
Silverlight Extended Canvas Control to Crop Images
Image cropping in action

Preface

CanvasExt is a part of the project Onym Silverlight Toolkit.

Introduction

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:

C#
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;
            Children.Add(_imgCroppable);
        }

        public WriteableBitmap CropImage()
        {
            try
            {
                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);
                }

                Children.Remove(_rectSelector);
                _rectSelector = null;
                return wbResult;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
        }

        private void canvasExt_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (_isRectSelectorMouseCaptured) return;
            if (!_isCanvasMouseCaptured && _isImageLoaded)
            {
                Children.Remove(_rectSelector);
                _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;
                Children.Add(_rectSelector);
                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:

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

Load the image into CanvasExt:

C#
BitmapImage bmp = new BitmapImage();
FileStream fs = imgOpenFileDialog.File.OpenRead();
bmp.SetSource(fs);
canvasExtTest.LoadFromBitmapImage(bmp);

And crop the image:

C#
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.

History

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

License

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


Written By
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
Kashif_Imran20-Jul-13 22:48 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan24-Aug-13 10:59
Onat Yiğit Mercan24-Aug-13 10:59 
GeneralRe: My vote of 2 Pin
Kashif_Imran24-Aug-13 11:09
Kashif_Imran24-Aug-13 11:09 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan24-Aug-13 11:26
Onat Yiğit Mercan24-Aug-13 11:26 
Questionmouse events for _rectSelector is not necessary Pin
quyun28-Jul-12 15:47
quyun28-Jul-12 15:47 
QuestionMy cropper Pin
darrellp26-Jan-12 20:12
darrellp26-Jan-12 20:12 
AnswerRe: My cropper Pin
Onat Yiğit Mercan27-Jan-12 10:16
Onat Yiğit Mercan27-Jan-12 10:16 
GeneralMy vote of 2 Pin
Georgi Atanasov17-Jan-12 11:03
Georgi Atanasov17-Jan-12 11:03 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan17-Jan-12 11:18
Onat Yiğit Mercan17-Jan-12 11:18 
GeneralRe: My vote of 2 Pin
Onat Yiğit Mercan20-Jan-12 9:06
Onat Yiğit Mercan20-Jan-12 9:06 
QuestionI was going to write Pin
Sacha Barber17-Jan-12 4:51
Sacha Barber17-Jan-12 4:51 
AnswerRe: I was going to write Pin
Onat Yiğit Mercan17-Jan-12 5:26
Onat Yiğit Mercan17-Jan-12 5:26 
It is great to see that a C# legend commented on my article Smile | :) I managed to write the code thanks to your article. Thank you!
GeneralRe: I was going to write Pin
Sacha Barber17-Jan-12 8:25
Sacha 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.