【问题标题】:Save Drawn Images PictureBox [duplicate]保存绘制的图像 PictureBox [重复]
【发布时间】:2020-06-17 21:15:16
【问题描述】:

我的程序允许用户绘制PictureBox

我正在尝试将 pictureBox1 保存为 .jpg 文件,但此文件为空。

我的保存按钮:

Bitmap bm = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
this.pictureBox1.DrawToBitmap(bm, this.pictureBox1.ClientRectangle);
bm.Save(String.Format("{0}.jpg", this.ID));
this.pictureBox1.CreateGraphics().Clear(Color.White);

我的抽奖活动:

private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
    drawNote.isDraw = true;
    drawNote.X = e.X;
    drawNote.Y = e.Y;
}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if(drawNote.isDraw)
    {
        Graphics G = pictureBox1.CreateGraphics();
        G.DrawLine(drawNote.pen, drawNote.X, drawNote.Y, e.X, e.Y);

        drawNote.X = e.X;
        drawNote.Y = e.Y;

    }
}

【问题讨论】:

    标签: c# bitmap draw picturebox drawtobitmap


    【解决方案1】:

    你应该通过这个位图创建一个空的Bimap set pictureBox1.Image 然后从中创建graphics,并且你必须将它存储在全局变量中以防止重新创建它。

    像这样:

    Graphics graphics = null;
    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if(drawNote.isDraw)
        {
            if (graphics == null) 
            {
              graphics = pictureBox1.CreateGraphics();
              Bitmap bmp = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.ClientSize.Height);
              pictureBox1.Image = bmp;
              graphics = Graphics.FromImage(bmp);
              graphics.Clear(Color.White);
            }
    
            graphics.DrawLine(drawNote.pen, drawNote.X, drawNote.Y, e.X, e.Y);
    
            graphics.Flush();
            graphics.Save();
            pictureBox1.Refresh();
    
            drawNote.X = e.X;
            drawNote.Y = e.Y;
        }
    }
    

    你可以通过这个简单的代码来做到这一点:

    using (FileStream fileStream = new FileStream(@"C:\test.jpg", FileMode.Create))
    {
        pictureBox1.Image.Save(fileStream, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    

    【讨论】:

    • 谢谢!我试过了,但是这个文件是空的。
    • @Ohy 我更改答案并进行测试。有用。试试看。
    • 它有效。谢谢!非常感谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2013-12-06
    相关资源
    最近更新 更多