如何使用 C# 裁剪图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/734930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:08:03  来源:igfitidea点击:

How to crop an image using C#?

c#image-processing

提问by sandy101

How can I write an application that will crop images in C#?

我如何编写一个应用程序,可以在 C# 中裁剪图像?

采纳答案by Daniel LeCheminant

You can use Graphics.DrawImageto draw a cropped image onto the graphics object from a bitmap.

您可以使用Graphics.DrawImage从位图将裁剪图像绘制到图形对象上。

Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using(Graphics g = Graphics.FromImage(target))
{
   g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), 
                    cropRect,                        
                    GraphicsUnit.Pixel);
}

回答by Nick

Check out this link: http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing

查看此链接:http: //www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing

private static Image cropImage(Image img, Rectangle cropArea)
{
   Bitmap bmpImage = new Bitmap(img);
   return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
}

回答by Guffa

It's quite easy:

这很容易:

  • Create a new Bitmapobject with the cropped size.
  • Use Graphics.FromImageto create a Graphicsobject for the new bitmap.
  • Use the DrawImagemethod to draw the image onto the bitmap with a negative X and Y coordinate.
  • 创建一个Bitmap具有裁剪大小的新对象。
  • 使用Graphics.FromImage创建Graphics对象的新位图。
  • 使用该DrawImage方法将图像绘制到具有负 X 和 Y 坐标的位图上。

回答by JohnFx

Assuming you mean that you want to take an image file (JPEG, BMP, TIFF, etc) and crop it then save it out as a smaller image file, I suggest using a third party tool that has a .NET API. Here are a few of the popular ones that I like:

假设您的意思是要获取图像文件(JPEG、BMP、TIFF 等)并将其裁剪然后将其保存为较小的图像文件,我建议使用具有 .NET API 的第三方工具。以下是我喜欢的一些流行的:

LeadTools
Accusoft PegasusSnowbound Imaging SDK

LEADTOOLS
Accusoft飞马大雪成像SDK

回答by PsychoCoder

Here's a simple example on cropping an image

这是裁剪图像的简单示例

public Image Crop(string img, int width, int height, int x, int y)
{
    try
    {
        Image image = Image.FromFile(img);
        Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
        bmp.SetResolution(80, 60);

        Graphics gfx = Graphics.FromImage(bmp);
        gfx.SmoothingMode = SmoothingMode.AntiAlias;
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
        gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
        // Dispose to free up resources
        image.Dispose();
        bmp.Dispose();
        gfx.Dispose();

        return bmp;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return null;
    }            
}

回答by ChrisJJ

Simpler than the accepted answer is this:

比接受的答案更简单的是:

public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
{
    using (Bitmap nb = new Bitmap(r.Width, r.Height))
    using (Graphics g = Graphics.FromImage(nb))
    {
        g.DrawImage(b, -r.X, -r.Y);
        return nb;
    }
}

and it avoids the "Out of memory" exception risk of the simplest answer.

它避免了最简单答案的“内存不足”异常风险。

Note that Bitmapand Graphicsare IDisposablehence the usingclauses.

需要注意的是BitmapGraphicsIDisposable因此using条款。

EDIT: I find this is fine with PNGs saved by Bitmap.Saveor Paint.exe, but fails with PNGs saved by e.g. Paint Shop Pro 6- the content is displaced. Addition of GraphicsUnit.Pixelgives a different wrong result. Perhaps just these failing PNGs are faulty.

编辑:我发现这对于由Bitmap.Save或 Paint.exe保存的 PNG很好,但是对于由Paint Shop Pro 6保存的 PNG 失败- 内容被置换了。添加GraphicsUnit.Pixel给出了不同的错误结果。也许只是这些失败的 PNG 有问题。

回答by IntellyDev

use bmp.SetResolution(image.HorizontalResolution, image .VerticalResolution);

bmp.SetResolution(image.HorizontalResolution, image .VerticalResolution);

this may be necessary to do even if you implement best answer here especially if your image is real great and resolutions are not exactly 96.0

即使您在这里实现最佳答案,这也可能是必要的,尤其是如果您的图像非常好并且分辨率不完全是 96.0

My test example:

我的测试示例:

    static Bitmap LoadImage()
    {
        return (Bitmap)Bitmap.FromFile( @"e:\Tests\d_bigImage.bmp" ); // here is large image 9222x9222 pixels and 95.96 dpi resolutions
    }

    static void TestBigImagePartDrawing()
    {
        using( var absentRectangleImage = LoadImage() )
        {
            using( var currentTile = new Bitmap( 256, 256 ) )
            {
                currentTile.SetResolution(absentRectangleImage.HorizontalResolution, absentRectangleImage.VerticalResolution);

                using( var currentTileGraphics = Graphics.FromImage( currentTile ) )
                {
                    currentTileGraphics.Clear( Color.Black );
                    var absentRectangleArea = new Rectangle( 3, 8963, 256, 256 );
                    currentTileGraphics.DrawImage( absentRectangleImage, 0, 0, absentRectangleArea, GraphicsUnit.Pixel );
                }

                currentTile.Save(@"e:\Tests\Tile.bmp");
            }
        }
    }

回答by Mike

Cropping an image is very easy in C#. However, doing the stuff how are you going to manage the cropping of your image will be a little harder.

在 C# 中裁剪图像非常容易。但是,如何管理图像的裁剪会有点困难。

Sample below is the way how to crop an image in C#.

下面的示例是如何在 C# 中裁剪图像的方法。

var filename = @"c:\personal\images\horizon.png";
var img = Image.FromFile(filename);
var rect = new Rectangle(new Point(0, 0), img.Size);
var cloned = new Bitmap(img).Clone(rect, img.PixelFormat);
var bitmap = new Bitmap(cloned, new Size(50, 50));
cloned.Dispose();

回答by Cem

There is a C# wrapper for that which is open source, hosted on Codeplex called Web Image Cropping

有一个 C# 包装器,它是开源的,托管在 Codeplex 上,称为Web Image Cropping

Register the control

注册控件

<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>

<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>

Resizing

调整大小

<asp:Image ID="Image1" runat="server" ImageUrl="images/328.jpg" />
<cs:CropImage ID="wci1" runat="server" Image="Image1" 
     X="10" Y="10" X2="50" Y2="50" />

Cropping in code behind- Call Crop method when button clicked for example;

在后面的代码中裁剪- 例如,单击按钮时调用 Crop 方法;

wci1.Crop(Server.MapPath("images/sample1.jpg"));

wci1.Crop(Server.MapPath("images/sample1.jpg"));

回答by user2757577

Only this sample working without problem:

只有这个示例工作没有问题:

var crop = new Rectangle(0, y, bitmap.Width, h);
var bmp = new Bitmap(bitmap.Width, h);
var tempfile = Application.StartupPath+"\"+"TEMP"+"\"+Path.GetRandomFileName();


using (var gr = Graphics.FromImage(bmp))
{
    try
    {
        var dest = new Rectangle(0, 0, bitmap.Width, h);
        gr.DrawImage(image,dest , crop, GraphicsUnit.Point);
        bmp.Save(tempfile,ImageFormat.Jpeg);
        bmp.Dispose();
    }
    catch (Exception)
    {


    }

}