1

I want convert Graphic was drawn to byte[] array. This code will show everybody my ideas.

        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

As you can see, after perform draw newGraphics is an image that has been drawn.

My idea got here, i don't know how to convert it to byte[] Because i still don't understand System.Drawing.Graphics of C#

Hope everybody help me. Thanks

Edward Ha
  • 19
  • 5

1 Answers1

1

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

When you use

Graphics newGraphics = Graphics.FromImage(image)

what you're basically doing is taking that original image and drawing directly to it using the Graphics methods.

When you're done drawing with Graphics you could just save the image or convert the image to a byte[].

Make sure to also Dispose() of the Graphics when your done as well, since it uses resources like memory and other [IDisposable][4] objects that need to be cleaned up before they can be collected by the Garbage Collector

DekuDesu
  • 2,224
  • 1
  • 5
  • 19
  • So when I convert image to byte[] array, it already includes the drawing, right? – Edward Ha May 15 '21 at 13:44
  • Yup! Any commands you run on the `Graphics` and you finish by using `Graphics`.`DrawImage(image...)` the original `image` should contain the newly drawn stuff – DekuDesu May 15 '21 at 13:49
  • Checkout [this post](https://stackoverflow.com/questions/1147156/graphics-object-to-image-file) it has really good examples on how to use the `Graphics` to draw onto an `image` and save it – DekuDesu May 15 '21 at 13:50