裁剪图像.Net

noo*_*bot 2 .net c#

我试图做一个简单的图像裁剪,但由于某种原因,它不尊重我的起始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;
Run Code Online (Sandbox Code Playgroud)

裁剪方法:

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;
    }  
Run Code Online (Sandbox Code Playgroud)

这应该很简单,但由于某种原因它不起作用.它裁剪它,只有0,0.

谢谢!

Mar*_*rco 5

你应该尝试使用

g.DrawImage(source, section);
Run Code Online (Sandbox Code Playgroud)

无论如何这个功能有效:

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我的错!裁剪工作正在进行,但是在我转向灰度后我还有其他代码,忘了改变我重新绘制的图像.使用的是原始图像,而不是新的裁剪图像,所以看起来它没有移动.对不起大家!我猜我应该发布所有这些内容. (2认同)