我正在尝试对图像进行简单的裁剪,但由于某种原因,它不尊重我的起始 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/