c# - 裁剪图像 .Net

标签 c# .net

我正在尝试对图像进行简单的裁剪,但由于某种原因,它不尊重我的起始 x,y 位置。它总是从 0,0 开始裁剪。以下是我正在做的事情:

Bitmap original = new Bitmap(pictureBox1.Image);

        int x = Convert.ToInt32(txtX.Text);
        int y = Convert.ToInt32(txtY.Text);
        int dX = Convert.ToInt32(txtDeltaX.Text);
        int dY = Convert.ToInt32(txtDeltaY.Text);

        Point loc = new Point(x, y);
        Size cropSize = new Size(dX, dY);

        Rectangle cropArea = new Rectangle(loc, cropSize);

        Bitmap bmpCrop = CropImage(original, cropArea);

        pictureBox1.Image = bmpCrop;

裁剪方法:

public Bitmap CropImage(Bitmap source, Rectangle section)
    {
        // An empty bitmap which will hold the cropped image  
        Bitmap bmp = new Bitmap(section.Width, section.Height);
        Graphics g = Graphics.FromImage(bmp);
        // Draw the given area (section) of the source image  
        // at location 0,0 on the empty bitmap (bmp)  
        g.DrawImage(source, 0, 0, section, GraphicsUnit.Pixel);
        return bmp;
    }  

这应该非常简单,但由于某种原因它不起作用。它会将其裁剪在 0,0 处。

谢谢!

最佳答案

你应该尝试使用

g.DrawImage(source, section);

无论如何,这个功能有效:

public Bitmap CropBitmap(Bitmap bitmap, 
                         int cropX, int cropY, 
                         int cropWidth, int cropHeight)
{
    Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
    Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
    return cropped;
}

关于c# - 裁剪图像 .Net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7893979/

相关文章:

c# - Windows 服务意外终止

c# - 是否有实现异步游戏引擎循环的最佳实践?

c# - 从代码访问 MVVM Light ViewModelLocator

c# - 如何使用 Visual Studio 2008 部署 asp.net 应用程序

c# - 将 .js 文件添加为来自服务器的 html 文件中的源

c# - 如何以编程方式运行 NUnit

c# - WPF 如何动态创建文本框并在单击按钮时找到文本框?

c# - 方法的类型参数与其外部类型相同

.net - 即使添加引用后也找不到 LinqPad Linq Include() 扩展方法

c# - 如何使用 Selenium C# PhantomJSDriver 设置 http referer header ?