我有一个我在屏幕上绘制的Graphics对象,我需要将其保存到png或bmp文件中.图形似乎不直接支持,但必须以某种方式.
步骤是什么?
Cur*_*lop 24
这是代码:
Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(bitmap);
// Add drawing commands here
g.Clear(Color.Green);
bitmap.Save(@"C:\Users\johndoe\test.png", ImageFormat.Png);
Run Code Online (Sandbox Code Playgroud)
如果您的图形在表单上,您可以使用:
private void DrawImagePointF(PaintEventArgs e)
{
... Above code goes here ...
e.Graphics.DrawImage(bitmap, 0, 0);
}
Run Code Online (Sandbox Code Playgroud)
此外,要保存在网页上,您可以使用:
MemoryStream memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Png);
var pngData = memoryStream.ToArray();
<img src="data:image/png;base64,@(Convert.ToBase64String(pngData))"/>
Run Code Online (Sandbox Code Playgroud)
图形对象是GDI +绘图表面.它们必须具有附加的设备上下文来绘制,即表单或图像.
将其复制到a Bitmap然后调用位图的Save方法.
需要注意的是,如果你从字面上绘制到屏幕(通过抓取屏幕的设备上下文),那么唯一的办法救你刚才画的屏幕是通过绘制的逆过程,从屏幕到一个Bitmap.这是可能的,但直接绘制到Bitmap(使用与绘制到屏幕相同的代码)显然要容易得多.
小智 5
试试这个,对我来说很好...
private void SaveControlImage(Control ctr)
{
try
{
var imagePath = @"C:\Image.png";
Image bmp = new Bitmap(ctr.Width, ctr.Height);
var gg = Graphics.FromImage(bmp);
var rect = ctr.RectangleToScreen(ctr.ClientRectangle);
gg.CopyFromScreen(rect.Location, Point.Empty, ctr.Size);
bmp.Save(imagePath);
Process.Start(imagePath);
}
catch (Exception)
{
//
}
}
Run Code Online (Sandbox Code Playgroud)