C#在小顶部裁剪图像

时间:2009-04-27 18:34:05

标签: c#

我有一个图像,我想裁剪图像的顶部并将图像保存在C#中。我该怎么办呢?

4 个答案:

答案 0 :(得分:5)

这里有一些cropping code记录良好:

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

答案 1 :(得分:1)

您可以创建所需大小的新位图,并使用Graphics.FromImage将旧图像的一部分绘制到新图像,以创建绘制到新图像中的Graphics对象。完成后,请确保Dispose of Graphics对象,然后您可以保存新创建的图像。

答案 2 :(得分:1)

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

答案 3 :(得分:1)

其他答案可行,以下是为Image创建extension method的方法:

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