Elfoc
Elfoc

Reputation: 3689

Saving inside of rectangle in picturebox

I have something like that - image loaded from file to picturebox1:

enter image description here

then after pressing button 'SelectArea' i can draw rectangle on loaded picture:

enter image description here

and finally after pressing another button 'SaveArea' i'd like to save img inside of created rectangle, so as a result i'll have image saved on my drive like this one:

enter image description here

How to write code which help me do this last step -> save inside of rectangle?

Tnx.

Upvotes: 0

Views: 2765

Answers (1)

Random Dev
Random Dev

Reputation: 52270

First new up a Bitmap with the right dimensions

then you create a Graphics-object for this with Graphics.FromImage and then use the DrawImage method on the resulting Graphics-object to draw a section of your large image onto the bitmap.

Finally save the bitmap-object with Save:

public static void SaveBitmapPart(System.Drawing.Image image, System.Drawing.RectangleF sourceRect, string pathToSave )
{
    using (var bmp = new System.Drawing.Bitmap((int)sourceRect.Width, (int)sourceRect.Height))
    {
        using (var graphics = System.Drawing.Graphics.FromImage(bmp))
        {
            graphics.DrawImage(image, 0.0f, 0.0f, sourceRect, System.Drawing.GraphicsUnit.Pixel);
        }
        bmp.Save(pathToSave);
    }
}

so just call it with:

SaveBitmapPart(picturebox1.Image, myRectangle, @"c:\Temp\Test.bmp");

Upvotes: 1

Related Questions