C#: Create Dynamic Image For Byte Array Data

So you have a unit test, but maybe for some reason you need to create an object that has a constructor that needs a byte array. Maybe for some reason that byte array needs to have more than 0 length. Maybe you don’t have any of this and you are just curious. Maybe I’ve said maybe too much.

Well in any case, here’s a way to do this:

using System.Drawing;
using System.IO;

    private byte[] GetBitmapData()
    {
      //Create the empty image.
      Bitmap image = new Bitmap(50, 50);

      //draw a useless line for some data
      Graphics imageData = Graphics.FromImage(image);
      imageData.DrawLine(new Pen(Color.Red), 0, 0, 50, 50);

      //Convert to byte array
      MemoryStream memoryStream = new MemoryStream();
      byte[] bitmapData;

      using (memoryStream)
      {
        image.Save(memoryStream, ImageFormat.Bmp);
        bitmapData = memoryStream.ToArray();
      }
      return bitmapData;
    }

And presto you have a fake image to send through. Can’t get much easier than that. Well maybe it could but not in this example. Why are you judging me? I’m just trying to help. You know what? Go away. I don’t want you around here anymore. You and those beady, judging eyes. Always looking… Never stopping… WHY DON’T YOU LEAVE ME ALONE?!?!?

One thought on “C#: Create Dynamic Image For Byte Array Data”

  1. Perfect!   Exactly what I needed to dynamically generate a blank image when the requested image was missing.

    Only instead of drawing a line, I used:
    imageData.Clear(Color.Transparent);

    Then used the png format.
    image.Save(memoryStream, ImageFormat.Png);

    This returned a valid blank image.  🙂

    Thank you soo much.

Comments are closed.