我有一个图像。我想从图像的左侧裁剪 10 像素,从右侧裁剪 10 像素。我使用下面的代码来执行此操作
string oldImagePath="D:\\RD\\dotnet\\Images\\photo1.jpg";
Bitmap myOriginalImage = (Bitmap)Bitmap.FromFile(oldImagePath);
int newWidth = myOriginalImage.Width;
int newHeight = myOriginalImage.Height;
Rectangle cropArea = new Rectangle(10,0, newWidth-10, newHeight);
Bitmap target = new Bitmap(cropArea.Width, cropArea.Height);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(myOriginalImage,cropArea);
}
target.Save("D:\\RD\\dotnet\\Images\\test.jpg");
但这并没有给我预期的结果。这输出一个从右侧裁剪了 10 px 的图像和一个调整大小的图像。它不是裁剪,而是调整我认为的宽度大小。所以图像被缩小(按宽度)。有人可以纠正我吗?提前致谢
最佳答案
您的新宽度应减少裁剪边距的两倍,因为您将从两侧切掉该量。
接下来,当将图像绘制到新图像中时,以负偏移量绘制它。这会导致您不感兴趣的区域被剪掉。
int cropX = 10;
Bitmap target = new Bitmap(myOriginalImage.Width - 2*cropX, myOriginalImage.Height);
using (Graphics g = Graphics.FromImage(target))
{
g.DrawImage(myOriginalImage, -cropX, 0);
}
关于C# : GDI+ Image cropping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1030278/