我想裁剪并调整图像大小。这是我的代码:
Image image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle.jpg");
// Crop and resize the image.
Rectangle destination = new Rectangle(0, 0, 200, 120);
Graphics graphic = Graphics.FromImage(image);
graphic.DrawImage(image, destination, int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(Width.Value), int.Parse(Height.Value), GraphicsUnit.Pixel);
现在,我假设将生成的裁剪/调整大小后的图像存储在图形对象中。问题是-如何将其保存到文件中?
最佳答案
从Graphics
获得的Graphics.FromImage
对象是图像的绘图表面。这样,您就可以在完成后简单地保存图像对象。
string fileName = AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle.jpg");
using (Image image = Image.FromFile(fileName)
{
using (Graphics graphic = Graphics.FromImage(image))
{
// Crop and resize the image.
Rectangle destination = new Rectangle(0, 0, 200, 120);
graphic.DrawImage(image, destination, int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(Width.Value), int.Parse(Height.Value), GraphicsUnit.Pixel);
}
image.Save(fileName);
}
请注意,在jpg图像上反复执行此操作可能不是一件好事;每次都会对图像进行重新编码,并且由于jpg使用破坏性的压缩方法,因此每次都会损失一些图像质量。不过,如果这是一次“每张图片”操作,则我不会担心。