簡體   English   中英

C#在較小的頂部裁剪圖像

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

我有一個圖像,我想裁剪圖像的頂部並將圖像保存在C#中。 我該怎么辦?

以下是一些有據可查的裁剪代碼

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

您可以創建一個所需大小的新位圖,然后使用Graphics.FromImage將舊圖像的一部分繪制到新圖像上,以創建一個可繪制到新圖像中的Graphics對象。 完成后,請確保處置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;
}

其他答案將起作用,這是通過為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