如何使用Web API处理图像

时间:2013-09-25 13:15:39

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

问题

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

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

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

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

2 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:22)

为了保存起见 - 这是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;
}

删除:

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

发表:

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