C# crop an image at small top portion

C# crop an image at small top portion

一笔一画续写前缘 发布于 2021-11-28 字数 116 浏览 886 回复 4 原文

I have an image and I want to crop the top portion of Image and save the image in C#. How can I go about it?

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。

扫码加入群聊

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

望她远 2022-06-07 4 楼

Other answers will work, here is how to do it by creating an extension method for Images:

class TestProgram
{
    static void Main()
    {
        using (Image testImage = Image.FromFile(@"c:file.bmp"))
        using (Image cropped = 
                     testImage.Crop(new Rectangle(10, 10, 100, 100)))
        {
            cropped.Save(@"c:cropped.bmp");
        }
    }
}

static public class ImageExtensions
{
    static public Bitmap Crop(this Image originalImage, Rectangle cropBounds)
    {
        Bitmap croppedImage = 
            new Bitmap(cropBounds.Width, cropBounds.Height);

        using (Graphics g = Graphics.FromImage(croppedImage))
        {
            g.DrawImage(originalImage,
                0, 0,
                cropBounds,
                GraphicsUnit.Pixel);
        }

        return croppedImage;
    }
}
明月夜 2022-06-07 3 楼
public static Bitmap Crop(Bitmap bitmap, Rectangle rect)
{
    // create new bitmap with desired size and same pixel format
    Bitmap croppedBitmap = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat);

    // create Graphics "wrapper" to draw into our new bitmap
    // "using" guarantees a call to gfx.Dispose()
    using (Graphics gfx = Graphics.FromImage(croppedBitmap))
    {
        // draw the wanted part of the original bitmap into the new bitmap
        gfx.DrawImage(bitmap, 0, 0, rect, GraphicsUnit.Pixel);
    }

    return croppedBitmap;
}
久光 2022-06-07 2 楼

You can create a new Bitmap of the desired size, and draw a portion of the old image to the new one using Graphics.FromImage to create a Graphics object that draws into the new image. Be sure to Dispose of the Graphics object when your're done, and then you can Save the newly-created image.

错々过的事 2022-06-07 1 楼

Here's some cropping code well documented:

 try
 {
    //create the destination (cropped) bitmap
    Bitmap bmpCropped = new Bitmap(100, 100);
    //create the graphics object to draw with
    Graphics g = Graphics.FromImage(bmpCropped);

    Rectangle rectDestination = new Rectangle(0, 0, bmpCropped.Width, bmpCropped.Height);
    Rectangle rectCropArea = new Rectangle(myX, myY, myCropWidth, myCropHeight);

    //draw the rectCropArea of the original image to the rectDestination of bmpCropped
    g.DrawImage(myOriginalImage, rectDestination, rectCropArea,GraphicsUnit.Pixel);
    //release system resources
 }
 finally
 {
     g.Dispose();
 }