在C#裁剪图像 [英] Crop image in c#
问题描述
我有,我想裁剪当我按下窗体上的按钮图像。我按下按钮时运行下面的代码,但它不会做任何图像:
I have a image that I want to crop it when I press a button on the form. I have the following code that is run when the button is pressed, but it doesn't do anything to the image:
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);
}
我的形象实际上是形式与下面的活动窗口截图代码:
My image is actually a screenshot of the active window of the form with the following code:
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);
}
要完成这一点,同时按下按钮,首先我要采取何种形式的截图,然后裁剪该图像,但裁剪不起作用。这是为什么?
To finish this, at the press of the same button, first I want to take the screenshot of the form, then crop that image, but cropping doesn't work. Why is that?
推荐答案
您的代码是接近我一直在使用什么保存裁剪的图像。你错过了,你保存剪裁的图片部分。您需要裁剪后的图像写入字节流,然后将其保存到磁盘。我修改你的代码,这是未经测试,但不妨一试。
Your code is close to what I have been using for saving cropped images. You're missing the part where you save the cropped image. You need to write the cropped image to a byte stream then save it to disk. I modified your code, it's untested but give it a try.
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#裁剪图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!