简体   繁体   中英

Saving inside of rectangle in picturebox

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

在此处输入图片说明

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

在此处输入图片说明

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:

在此处输入图片说明

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

Tnx.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM