从控制台应用程序生成随机JPG图像 [英] Generating a Random JPG Image From Console Application

查看:68
本文介绍了从控制台应用程序生成随机JPG图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API,该API接受大小为80x20(JPG,PNG或GIF)的图像的base64string并存储在数据库中。为了测试此API,我必须生成一个随机的base64string,当解码时可以将其转换为真实图像。

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.

我找到了示例此处,它似乎可以与WPF应用程序一起使用。

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

推荐答案

应该使用多种方法。怎么样:

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());
        }
    }
}

请务必添加一个引用 System.Drawing

这篇关于从控制台应用程序生成随机JPG图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆