Cropping image part form main image using Bitmap

10 בJune 2016

תגובה אחת

It might be sound as complex work but it is actually an simple one,
The shortest implementation is based on Bitmap framework of System.Windows.Media.Imaging,
The first part of the challenge is to select a rectangle or something similar to be used as desired area of the cropped image, but selection itself is another discussion.. as for now assume you have an well defined box, every task of cropping inage part based on X location Y location Width and Height.
In reality, after you get the right coordinates you just need to activate the next fancy cropping service:

/// crop image part based on image path, point location over the image , and width,height of the crop itself

        private BitmapSource CutImage(string imgPath, int crpWidth, int crpHeight, int crpLocationX, int crpLocationY)


            BitmapImage originImage = new BitmapImage();


            originImage.UriSource = new Uri(imgPath);

            originImage.CacheOption = BitmapCacheOption.OnLoad;


            BitmapSource bs = new CroppedBitmap(new BitmapImage(new Uri(imgPath)), new Int32Rect( crpLocationX, crpLocationY ,crpWidth, crpHeight));

            return bs;


        //create the output result on out put folder

        private void ExportCroppedImageToFile(BitmapSource bitmap, string filepath)


            // Encoding the RenderBitmapTarget as a PNG file.

            BmpBitmapEncoder bmp = new BmpBitmapEncoder();


            using (Stream stm = File.Create(filepath))





Now all you have to do is run it like:

private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)


          CutImage(this.image.Source.ToString(), 100, 100, 123, 234);


הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

תגובה אחת

  1. Nockout28 בJune 2016 ב 13:58

    well man it is lovely, yet is there a chance to have a full demo with ui selection tool ?