Asp.Net Core动态生成映像文件

mis*_*iga 1 c# asp.net image .net-core asp.net-core

如何在控制器中生成所有图像并将其作为图像文件返回?例如,如果链接是:

www.test.com/generate?width=100&height=50&color=red
Run Code Online (Sandbox Code Playgroud)

这将生成100x50的红色图像并将其返回,如果我将此链接设置为前面的图像视图源,则应绘制该图像.它应该作为一种服务,与HTML或其他平台(如iOS UIImageView和Android ImageView)没有任何连接.

mis*_*iga 6

我设法使用System.Drawing和System.Drawing.Drawing2D - Graphics类进行绘制

Bitmap bitmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

Graphics graphics = Graphics.FromImage(bitmap);

var pen = new Pen(lineColor, widthLine);

graphics.FillRectangle(new SolidBrush(bgColor), new Rectangle(0, 0, width, height));
Run Code Online (Sandbox Code Playgroud)

和图形有所有必要的绘图方法,绘制完成后使用位图创建图像文件并从ASP网络动作返回HttpResponseMessage

using (MemoryStream ms = new MemoryStream())
{
    bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new ByteArrayContent(ms.ToArray());
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这就是我想要的,而不是无用的投票:)

  • 在一个新的 .net 核心 web 应用程序中,我还必须安装 [`System.Drawing.Common`](https://www.nuget.org/packages/System.Drawing.Common) 另外,不要忘记处理所有这些资源(`Bitmap`、`Graphics`、`Pen`、`SolidBrush`) (2认同)