gpt4 book ai didi

c# - Asp.Net Core 动态生成图片文件

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:54 25 4
gpt4 key购买 nike

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

www.test.com/generate?width=100&height=50&color=red

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

最佳答案

我设法使用 System.Drawing 和 System.Drawing.Drawing2D 绘图 - 图形类

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

图形具有绘制所需的所有方法,绘制完成后使用位图创建图像文件并从 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;
}

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

关于c# - Asp.Net Core 动态生成图片文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47937591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com