首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用WebAPI处理图像

如何使用WebAPI处理图像
EN

Stack Overflow用户
提问于 2013-09-25 21:15:39
回答 2查看 68.7K关注 0票数 45

问题

  1. 向我的服务发布/获取图像的不同方式有哪些?我认为我既可以在JSON中使用Base-64文本,也可以保持原生为二进制。我的理解是,通过将图像转换为文本,会显著增加包的大小。
  2. 如果我发送图像(从web表单、本机客户端或其他服务),我应该添加图像控制器/处理程序还是使用格式化程序?这是一个非此即彼的问题吗?

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

有没有一篇网站/博客文章列出了这种做法的利弊?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-01 17:54:07

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

票数 29
EN

Stack Overflow用户

发布于 2016-09-13 15:03:01

为了保护--以下是Jamie博客的提纲:

使用控制器:

获取:

代码语言:javascript
复制
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;
}

删除:

代码语言:javascript
复制
public void Delete(int id)
{
    String filePath = HostingEnvironment.MapPath("~/Images/HT.jpg");
    File.Delete(filePath);
}

帖子:

代码语言:javascript
复制
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"));
    } 
}
票数 27
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19005991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档