我有一张Pic例如(这张图片有X:467 Y:300)我只需要从X:0 Y:0到X:200 Y:45我使用此代码进行裁剪但我丢失了X的数据:0 Y:0到X:200 Y:45我不知道该怎么做
bmp.Save("@image.png", ImageFormat.Png);
Image img = new Bitmap("@image.png");
Rectangle source = new Rectangle(0, 0, ww, hh);
Image cropped = CropImage(img, source);
cropped.Save(Path.GetDirectoryName("@image.png") + "croppped" + Path.GetExtension("@image.png"));
}
private Bitmap CropImage(Image originalImage, Rectangle sourceRectangle,Rectangle? destinationRectangle = null)
{
if (destinationRectangle == null)
{
destinationRectangle = new Rectangle(Point.Empty, sourceRectangle.Size);
}
var croppedImage = new Bitmap(destinationRectangle.Value.Width,
destinationRectangle.Value.Height);
using (var graphics = Graphics.FromImage(croppedImage))
{
graphics.DrawImage(originalImage, destinationRectangle.Value,
sourceRectangle, GraphicsUnit.Pixel);
}
return croppedImage;
}
答案 0 :(得分:0)
根据我的理解,您希望在将原始图像保存到磁盘之前裁剪图像。在这种情况下,您可以直接将图像提供给裁剪方法:
// bmp.Save("@image.png", ImageFormat.Png);
// Image img = new Bitmap("@image.png");
Rectangle source = new Rectangle(0, 0, ww, hh);
Image cropped = CropImage(bmp, source); // <-- bmp supplied to crop method directly
cropped.Save(Path.GetDirectoryName("@image.png") + "croppped" + Path.GetExtension("@image.png"));