5

I have an API that takes the base64string of an image of size 80x20(either JPG, PNG or GIF) and stores in database. In order to test this API I have to generate a random base64string which can be converted into a real image when decoded.

I have find the example here which seems to work with WPF application. How to use the same for a console application?

Community
  • 1
  • 1
satya
  • 2,537
  • 9
  • 33
  • 43
  • What is the issue? Just add a reference to `System.Drawing`. – leppie May 21 '14 at 11:05
  • 1
    Well, only a subset of random Base64 strings can be converted to an Image. Maybe you actually want to create a random Image and convert it to a Base64 string. If you really need the image to be random, you'd better define what you mean by that, it might make your tests hard to reproduce. You should show your efforts in the question and define what your specific problem/issue/point is. – Jodrell May 21 '14 at 11:18
  • Code from OP http://stackoverflow.com/questions/20981467/how-to-create-a-byte-array-that-contains-a-real-image should work in console application. – Matas Vaitkevicius May 21 '14 at 11:38

1 Answers1

5

A variety of methods should work. How about the following:

public static string GenerateBase64ImageString()
{
    // 1. Create a bitmap
    using (Bitmap bitmap = new Bitmap(80, 20, PixelFormat.Format24bppRgb))
    {
        // 2. Get access to the raw bitmap data
        BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat);

        // 3. Generate RGB noise and write it to the bitmap's buffer.
        // Note that we are assuming that data.Stride == 3 * data.Width for simplicity/brevity here.
        byte[] noise = new byte[data.Width * data.Height * 3];
        new Random().NextBytes(noise);
        Marshal.Copy(noise, 0, data.Scan0, noise.Length);

        bitmap.UnlockBits(data);

        // 4. Save as JPEG and convert to Base64
        using (MemoryStream jpegStream = new MemoryStream())
        {
            bitmap.Save(jpegStream, ImageFormat.Jpeg);
            return Convert.ToBase64String(jpegStream.ToArray());
        }
    }
}

Just be sure to add a reference to System.Drawing.

TC.
  • 4,133
  • 3
  • 31
  • 33