API 图片请求问题 - URL 处的 FileNotFound

API Image Request Issue - FileNotFound at URL

我要实现的目标只是从 API 请求图像,然后 return 以 append 方法的形式将其发送到客户端.

NO,由于 API.

的 user/pass 要求,我不能完全在客户端处理这个问题

NO,我无法在图片的src中使用@Url.Action(ImageFromPath)方法。

也就是说,这是我的后端代码:

[HttpGet("api/GetImage")]
public ActionResult ImageFromPath()
{
    string URL = "http://user:pass@MYIPADDRESS/cgi-bin/snapshot.cgi?c=1&authbasic=asdf1234";

    var srcImage = Image.FromFile(URL);
    var stream = new MemoryStream();
    srcImage.Save(stream, ImageFormat.Png);
    return File(stream.ToArray(), "image/png");
}

客户端的目标是:

$http.get('/api/GetImage').then(function (response) {
    $("#imgDiv").append('<img src="data:image/png;base64,' + response.data + '" />');
});

我遇到的问题在线 srcImage = Image.FromFile(URL),错误:

An exception of type 'System.IO.FileNotFoundException' occurred in CoreCompat.System.Drawing.dll but was not handled in user code

如果有任何区别,调用 API URL 本身需要几秒钟才能 return 图片。

任何人都可以建议实现此目标的正确方法吗?或者至少有助于让我目前的方法发挥作用?

EDIT - 我查看了 How can I convert image url to system.drawing.image 的答案,但它只提供了使用 WebClient 的解决方案,这在 [=45] 中不可用=] 还没核心。

如果您想从 URL 读取文件,您需要使用 HttpClient.

FilesController.cs

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DemoWebCore.Controllers
{
    [Route("api/[controller]")]
    public class FilesController : Controller
    {
        // GET api/files/sample.png
        [HttpGet("{fileName}")]
        public async Task<string> Get(string fileName)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = await client.GetAsync(
                     "https://i.stack.imgur.com/hM8Ah.jpg?s=48&g=1");
                byte[] content = await response.Content.ReadAsByteArrayAsync();
                return "data:image/png;base64," + Convert.ToBase64String(content);
            }
        }
    }
}

用法

HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace DemoWebCore.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
} 

查看

<img id="sample-img" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        var url = "/api/files/sample.png";
        $.get(url, function (data) {
            console.log(data);
            $("#sample-img").attr('src', data);
        });
    })
</script>

你原来是在从文件系统中读取一个文件。如果该文件位于您的 wwwroot 文件夹中, 回答可能会对您有所帮助。