简体   繁体   English

C#在较小的顶部裁剪图像

[英]C# crop an image at small top portion

I have an image and I want to crop the top portion of Image and save the image in C#. 我有一个图像,我想裁剪图像的顶部并将图像保存在C#中。 How can I go about it? 我该怎么办?

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();
 } 

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. 您可以创建一个所需大小的新位图,然后使用Graphics.FromImage将旧图像的一部分绘制到新图像上,以创建一个可绘制到新图像中的Graphics对象。 Be sure to Dispose of the Graphics object when your're done, and then you can Save the newly-created image. 完成后,请确保处置Graphics对象,然后可以保存新创建的图像。

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;
}

Other answers will work, here is how to do it by creating an extension method for Image s: 其他答案将起作用,这是通过为Image创建扩展方法来实现的方法

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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