gpt4 book ai didi

c# - 在 C# 中裁剪图像

转载 作者:行者123 更新时间:2023-11-30 12:14:06 24 4
gpt4 key购买 nike

我有一张图片,当我按下表单上的按钮时,我想裁剪它。我有以下代码在按下按钮时运行,但它对图像没有任何作用:

try
{
Image image = Image.FromFile("test.jpg");
Bitmap bmp = new Bitmap(200, 200, PixelFormat.Format24bppRgb);
bmp.SetResolution(80, 60);

Graphics gfx = Graphics.FromImage(bmp);
gfx.SmoothingMode = SmoothingMode.AntiAlias;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfx.DrawImage(image, new Rectangle(0, 0, 200, 200), 10, 10, 200, 200, GraphicsUnit.Pixel);
// Dispose to free up resources
image.Dispose();
bmp.Dispose();
gfx.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

我的图片其实是窗体事件窗口的截图,代码如下:

Rectangle bounds = this.Bounds;
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
bitmap.Save("test.jpg", ImageFormat.Jpeg);
}

要完成此操作,请按同一个按钮,首先我想截取表单的屏幕截图,然后裁剪该图像,但裁剪不起作用。这是为什么?

最佳答案

您的代码与我用来保存裁剪图像的代码很接近。您缺少保存裁剪图像的部分。您需要将裁剪后的图像写入字节流,然后将其保存到磁盘。我修改了您的代码,它未经测试,但请尝试一下。

try
{
Image image = Image.FromFile("test.jpg");
Bitmap bmp = new Bitmap(200, 200, PixelFormat.Format24bppRgb);
bmp.SetResolution(80, 60);

Graphics gfx = Graphics.FromImage(bmp);
gfx.SmoothingMode = SmoothingMode.AntiAlias;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfx.DrawImage(image, new Rectangle(0, 0, 200, 200), 10, 10, 200, 200, GraphicsUnit.Pixel);

//Need to write the file to memory then save it
MemorySteam ms = new MemoryStream();
bmp.Save(ms, image.RawFormat);
byte[] buffer = ms.GetBuffer();

var stream = new MemorySteam((buffer), 0, buffer.Length);
var croppedImage = SD.Image.FromStream(steam, true);
croppedImage.Save("/your/path/image.jpg", croppedImage.RawFormat);

// Dispose to free up resources
image.Dispose();
bmp.Dispose();
gfx.Dispose();
stream.Dispose();
croppedImage.Dispose();

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

关于c# - 在 C# 中裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10316941/

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