如何将面板另存为 BMP
Posted
技术标签:
【中文标题】如何将面板另存为 BMP【英文标题】:How to save Panel as BMP 【发布时间】:2013-02-03 15:32:12 【问题描述】:我正在尝试将面板上的图像保存为 BMP,但无论何时保存,都只有一个空白图像。
绘图代码
private void DrawingPanel_MouseMove(object sender, MouseEventArgs e)
OldPoint = NewPoint;
NewPoint = new Point(e.X, e.Y);
if (e.Button == MouseButtons.Left)
Brush brush = new SolidBrush(Color.Red);
Pen pen = new Pen(brush, 1);
DrawingPanel.CreateGraphics().DrawLine(pen, OldPoint, NewPoint);
保存代码
void SaveBMP(string location)
Bitmap bmp = new Bitmap((int)DrawingPanel.Width, (int)DrawingPanel.Height);
DrawingPanel.DrawToBitmap(bmp, new Rectangle(0, 0, DrawingPanel.Width, DrawingPanel.Height));
FileStream saveStream = new FileStream(location + ".bmp", FileMode.OpenOrCreate);
bmp.Save(saveStream, ImageFormat.Bmp);
saveStream.Flush();
saveStream.Close();
最终结果
这是我画的
这就是节省
【问题讨论】:
好吧,您必须将绘画放在面板的绘画事件中,因为面板不会保存您只需“动态”添加的 DrawLine。 您是否尝试过覆盖面板并在覆盖的 OnPaint 方法中对其进行绘制?这是像这样的自定义控件绘图要遵循的一般模式。对我来说,您当前的代码不起作用是有道理的,因为 DrawBitmap 方法可能会再次绘制整个控件,而不是绘制您当前在屏幕上看到的任何内容。 @steinar 我该怎么做呢?能否举例回复一下,谢谢。 【参考方案1】:您必须更改代码以覆盖 OnPaint 方法。这是自定义控件外观时遵循的默认模式。
您的特定代码不起作用的原因是 DrawToBitmap 必须在调用时重绘整个控件。在这种情况下,该方法不知道您对控件的自定义绘图。
这是一个工作示例:
public partial class DrawingPanel : Panel
private List<Point> drawnPoints;
public DrawingPanel()
InitializeComponent();
drawnPoints = new List<Point>();
// Double buffering is needed for drawing this smoothly,
// else we'll experience flickering
// since we call invalidate for the whole control.
this.DoubleBuffered = true;
protected override void OnPaint(PaintEventArgs e)
base.OnPaint(e);
// NOTE: You would want to optimize the object allocations,
// e.g. creating the brush and pen in the constructor
using (Brush brush = new SolidBrush(Color.Red))
using (Pen pen = new Pen(brush, 1))
// Redraw the stuff:
for (int i = 1; i < drawnPoints.Count; i++)
e.Graphics.DrawLine(pen, drawnPoints[i - 1], drawnPoints[i]);
protected override void OnMouseMove(MouseEventArgs e)
base.OnMouseMove(e);
// Just saving the painted data here:
if (e.Button == System.Windows.Forms.MouseButtons.Left)
drawnPoints.Add(e.Location);
this.Invalidate();
public void SaveBitmap(string location)
Bitmap bmp = new Bitmap((int)Width, (int)Height);
DrawToBitmap(bmp, new Rectangle(0, 0, Width, Height));
using (FileStream saveStream = new FileStream(location + ".bmp", FileMode.OpenOrCreate))
bmp.Save(saveStream, ImageFormat.Bmp);
【讨论】:
以上是关于如何将面板另存为 BMP的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript 将元素另存为图像或 Extjs 4.x 另存为图像
一点控制面板 就跳出 Explorer.EXE 该文件没有与之关联的程序来执行该操作