C#中如何将Graphic was drawn to byte[]数组转换(byte[]也会包含绘图)

How to convert Graphic was drawn to byte[] array in C# (byte[] will also include drawings)

我想将绘制的图形转换为 byte[] 数组。这段代码将向大家展示我的想法。

        Graphics newGraphics = Graphics.FromImage(image);

            // Draw it
            Random rnd = new Random();
            Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
            Pen blackPen = new Pen(randomColor, 2);

            // Create rectangle.               
            Rectangle rect = new Rectangle(int.Parse(val[2]), int.Parse(val[3]), int.Parse(val[4]), int.Parse(val[5])); //val[x] is 4 point to make Rectangle

            // Draw rectangle.
            newGraphics.DrawRectangle(blackPen, rect);
            newGraphics.DrawString(lines[int.Parse(val[0])], new Font("font name", 4), Brushes.Red, rect); //draw string for name of Rectangle

可以看到,执行draw后newGraphics是一张已经绘制好的图片

我的想法来了,我不知道如何将它转换成byte[] 因为我还是不懂System.Drawing.Graphics of C#

希望大家帮帮我。谢谢

How to convert Graphic was drawn to byte[] array in C# (byte[] will also include drawings)

当你使用

Graphics newGraphics = Graphics.FromImage(image)

您基本上是在采用原始的 imagedrawing directly to it using the Graphics 方法。

Graphics 完成绘图后,您可以 just save the image or convert the image to a byte[].

确保在完成后 GraphicsDispose(),因为它使用内存和其他 [IDisposable][4] 对象等资源,需要在它们之前清理可以被垃圾收集器收集