winforms 如何保存图片框中的图像,包括上面绘制的图形?

qlvxas9a  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(131)

我要保存pictureBox1中的图像,包括图形。

private void pictureBox1_Paint(object sender, PaintEventArgs e)
         {
             e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
             e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
             e.Graphics.DrawRectangle(Pens.Green, 0, 0, pictureBox1.Width - 1, pictureBox1.Height - 1);
    
             Pen p = new Pen(Color.Red);
             e.Graphics.DrawLine(p, 256, 0, 256, 512);
             e.Graphics.DrawLine(p, 0, 256, 512, 256);
    
             DrawPieOnPicturebox(e.Graphics);
         }
    
         public void DrawPieOnPicturebox(Graphics myPieGraphic)
         {
             Color myPieColors = Color.FromArgb(150, Color.LightGreen);
             Size myPieSize = new Size((int)distanceFromCenterPixels, (int)distanceFromCenterPixels);
             Point myPieLocation = new Point((pictureBox1.Width - myPieSize.Width) / 2, (pictureBox1.Height - myPieSize.Height) / 2);
             DrawMyPie(myPiePercent, myPieColors, myPieGraphic, myPieLocation, myPieSize);
         }
    
         int counter = 0;
         public void DrawMyPie(int myPiePerecent, Color myPieColor, Graphics myPieGraphic, Point
       myPieLocation, Size myPieSize)
         {
             using (SolidBrush brush = new SolidBrush(myPieColor))
             {
                 myPieGraphic.FillPie(brush, new Rectangle(myPieLocation, myPieSize), Convert.ToSingle(myPiePerecent * 360 / 100), Convert.ToSingle(15 * 360 / 100));
             }
    
             myBitmap = new Bitmap(pictureBox1.Image);
             myBitmap.Save(@"d:\" + counter + "mybitmap1.bmp");
             myBitmap.Dispose();
             counter++;
         }

它正在pictureBox1中保存图像,但没有绘制的FillPie。我想将绘制的FillPie也添加到保存的位图中。

wdebmtf2

wdebmtf21#

我认为最好的办法是使用myPieGraphic.DrawImage,然后使用myPieGraphic.FillPie,最后使用保存方法。
目前还不清楚这是如何在您的应用程序分层,但我假设你有一个图片框中的图像,然后你画在它上面使用图形?
这样做将呈现到单独的“层”,可以说它们不是相同的图像/图形。如果你用相同的图形绘制图像和饼图,你可以直接保存它。
我想那会产生你想要的结果。
请参阅所有图形方法的链接:https://learn.microsoft.com/en-us/dotnet/api/system.drawing.graphics.addmetafilecomment?view=dotnet-plat-ext-7.0
编辑:回答评论。

using(MemoryStream ms = new MemoryStream()) {
    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    using (var fs = new FileStream(@"c:\temp\test.png", FileMode.Create))
    {
        var bytes = ms.ToArray();
        await fs.WriteAsync(bytes , 0, bytes.Length);
    }
}

相关问题