Generating a Random JPG Image From Console Application

家住魔仙堡 提交于 2019-12-14 00:33:36

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/23781364/generating-a-random-jpg-image-from-console-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!