satya
satya

Reputation: 2607

Generating a Random JPG Image From Console Application

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?

Upvotes: 5

Views: 3666

Answers (1)

TC.
TC.

Reputation: 4183

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.

Upvotes: 5

Related Questions