无法从C#中的System.Drawing.Image渲染图像

时间:2019-09-20 13:47:35

标签: c# image asp.net-web-api

我正在尝试从BlobUrl获取图像,但是它无法在浏览器中呈现。

我的代码控制器:

[HttpGet]
public System.Drawing.Image GetImage()
{

    var profileImage = Db.Candidate.Include(x => x.ProfileImage).AsNoTracking().Single().ProfileImage;
    var urlWithSharedAccessToken = _fileService.GetBlobUrl(profileImage.FileGuid, DateTime.Now.AddHours(1));

    WebClient wc = new WebClient();
    byte[] bytes = wc.DownloadData(urlWithSharedAccessToken);
    MemoryStream ms = new MemoryStream(bytes);
    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

    return img;
}

下面是浏览器响应:

enter image description here

任何人都可以告诉我,我应该怎么做才能从 System.Drawing.Image

渲染实际图像

1 个答案:

答案 0 :(得分:1)

我已经使用ByteArrayContent返回了HttpResponseMessage。我的完整代码:

[HttpGet]
[Route("profile_image")]
public async Task<IHttpActionResult> GetProfileImageData()
{
    var profileImage = Db.Candidate.Include(x => x.ProfileImage).AsNoTracking().Single().ProfileImage;

    using (var file = await _fileService.DownloadFileAsync(profileImage.FileGuid))
    {
        var memory = new MemoryStream();
        await file.CopyToAsync(memory);

        // Create response message
        var message = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ByteArrayContent(memory.ToArray())
        };

        //Otroligt att man ska behöva kladda med detta, men "filename" i Content Disposition accepterar enbart us-ascii strängar i vissa webbläsare
        var encoder = Encoding.GetEncoding("us-ascii", new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback());
        string asciiFileName = encoder.GetString(encoder.GetBytes(profileImage.FileName));

        // Set content headers
        message.Content.Headers.ContentLength = memory.Length;
        message.Content.Headers.ContentType = new MediaTypeHeaderValue(profileImage.ContentType ?? "application/octet-stream");
        message.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = asciiFileName,
            Size = file.Length
        };

        return new ResponseMessageResult(message);
    }
}