如何使用WebAPI处理图像

Jam*_*xon 42 asp.net image asp.net-web-api

问题

  1. POST/GET图像到我的服务有哪些不同的方法?我想我可以在JSON中使用Base-64文本,也可以将本机保留为二进制文件.我的理解是,通过将图像转换为文本,包装尺寸显着增加.

  2. 如果我发送图像(来自网络表单,来自本机客户端,来自其他服务),我应该添加图像控制器/处理程序还是使用格式化程序?这甚至是一个问题还是问题?

我已经研究过并发现了许多相互竞争的例子,但我不确定我应该走向哪个方向.

是否有网站/博客文章列出了这方面的利弊?

Jam*_*xon 26

我做了一些研究,你可以看到我在这里提出的实现:http: //jamessdixon.wordpress.com/2013/10/01/handling-images-in-webapi/

  • 一旦链接断开,这个答案就没用了. (10认同)

Ask*_* B. 23

为了保存起见 - 这是Jamie的博客所说的概述:

使用控制器:

得到:

public HttpResponseMessage Get(int id)
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");
    FileStream fileStream = new FileStream(filePath, FileMode.Open);
    Image image = Image.FromStream(fileStream);
    MemoryStream memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Jpeg);
    result.Content = new ByteArrayContent(memoryStream.ToArray());
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");

    return result;
}
Run Code Online (Sandbox Code Playgroud)

删除:

public void Delete(int id)
{
    String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");
    File.Delete(filePath);
}
Run Code Online (Sandbox Code Playgroud)

帖子:

public HttpResponseMessage Post()
{
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    if (Request.Content.IsMimeMultipartContent())
    {
        //For larger files, this might need to be added:
        //Request.Content.LoadIntoBufferAsync().Wait();
        Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(
                new MultipartMemoryStreamProvider()).ContinueWith((task) =>
        {
            MultipartMemoryStreamProvider provider = task.Result;
            foreach (HttpContent content in provider.Contents)
            {
                Stream stream = content.ReadAsStreamAsync().Result;
                Image image = Image.FromStream(stream);
                var testName = content.Headers.ContentDisposition.Name;
                String filePath = HostingEnvironment.MapPath("~/Images/");
                //Note that the ID is pushed to the request header,
                //not the content header:
                String[] headerValues = (String[])Request.Headers.GetValues("UniqueId");
                String fileName = headerValues[0] + ".jpg";
                String fullPath = Path.Combine(filePath, fileName);
                image.Save(fullPath);
            }
        });
        return result;
    }
    else
    {
        throw new HttpResponseException(Request.CreateResponse(
                HttpStatusCode.NotAcceptable,
                "This request is not properly formatted"));
    } 
}
Run Code Online (Sandbox Code Playgroud)