gpt4 book ai didi

c# - 图形对象到图像文件

转载 作者:太空狗 更新时间:2023-10-29 17:38:42 24 4
gpt4 key购买 nike

我想裁剪和调整我的图像。这是我的代码:

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 获得的 Graphics 对象是图像的绘图表面。因此,您可以在完成后简单地保存图像对象。

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 使用破坏性压缩方法,所以每次都会损失一些图像质量。不过,如果这是对每张图片进行一次操作,我不会担心这一点。

关于c# - 图形对象到图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1147156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com