【问题标题】:Returning an image in a web service在 Web 服务中返回图像
【发布时间】:2019-06-08 07:26:37
【问题描述】:

我正在开发一个基本的网络服务。用户发送一个 base 64 字符串,并且服务必须返回一个图像。

我有这门课:

public class myImage
{    
    public Byte[] Matrix { get; set; }        
    public int Width { get; set; }
    public int Height { get; set; }
}

矩阵是一个包含灰度像素值的字节数组。

我看到很多关于将字节数组转换为图像的主题(如this onethis one),但它对我不起作用。我添加了对 System.Drawing 的引用,但出现错误:

在命名空间“System.Drawing”中找不到类型名称“Image”。此类型已转发到程序集 'System.Drawing.Common, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' 考虑添加对该程序集的引用。

我看到我必须返回一个FileResult,但如果我不能使用System.Drawing.Image,我就无法创建结果:

[HttpPost]
[Route("CreateImage")]
public FileResult PostSealCryptItem([FromBody]String base64)
{
    MyImage myImg = createImg(base64);

    FileResult result = ?;
    return result;
}

如何从我的字节数组创建FileResult

【问题讨论】:

  • 我觉得应该是FileResult
  • 如果使用 Asp 核心文件结果有效。检查下面的答案。我觉得还是少了点什么。确保 base64 格式如下:data:image/png;base64,iVBORw0KGgoAAA ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4 //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU 5ErkJggg==
  • 不要返回System.Drawing.Image。该类用于操作图像。您也不能只返回一个像素矩阵,您必须先创建要返回的实际字节。一旦你有了实际的字节缓冲区或流,你可以用 return File(bytes,...)return File(stream,...) 来返回它们

标签: c# asp.net-core .net-core-2.1


【解决方案1】:

你可以这样做。

public HttpResponseMessage  PostSealCryptItem([FromBody]String base64)
{
    MyImage myImg = createImg(base64);
    Image img = convertMyImgToImage(myImg);
    using(MemoryStream ms = new MemoryStream())
    {
        img.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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    相关资源
    最近更新 更多