【问题标题】:How to handle png from rest api?如何处理来自rest api的png?
【发布时间】:2019-03-22 20:09:39
【问题描述】:

现在,我正在创建一个 WCF 服务,该服务将位置发送到 Bing 地图 API 并将 PNG 图像返回给服务客户端。目前,我从他们的文档网页复制了一个有效的 api 示例,但我很难弄清楚如何传递它。

从其他 stackoverflow 问题开始,我首先将响应转换为 Base64。但它触发并收到一个错误,说输入不是Base64 形式。

A screenshot of what input looks like

public string getResponse()
{
    string key = [My Api Key];

    Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, key));
    Uri imageryRequest = new Uri(string.Format("https://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Redmond Washington?ms=500,270&zl=12&&c=en-US&he=1&key={0}", key));

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imageryRequest);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    //Handling the response in PNG
    Stream stream = response.GetResponseStream();
    StreamReader reader = new StreamReader(stream);

    string input = reader.ReadToEnd();

    byte[] data = convert.FromBase64String(input);
    return data;


}

【问题讨论】:

  • 您附加的图像在文本编辑器中打开时看起来像 PNG 文件的标题。尝试改为读取 ByteArray 并将其保存到文件中。

标签: c# asp.net rest http wcf


【解决方案1】:

它已经是byte[] 的PNG 图像。另外,请记住,返回的图像不能保证为PNGJPEGGIF。它返回它认为最合适的图像类型,除非a specific type is requested

例如。 fmt=jpeg

你只需要对它做点什么。在我的示例中,我将其保存到文件中。您可能只需要返回byte[]

private static HttpClient client = new HttpClient();
public static async void GetResponse()
{
    string key = Properties.Settings.Default.Key;

    Uri imgUri = new Uri($"https://dev.virtualearth.net/REST/v1/Imagery/Map/Road/Redmond Washington?ms=500,270&zl=12&&c=en-US&he=1&fmt=png&key={key}");

    HttpResponseMessage response = await client.GetAsync(imgUri);
    response.EnsureSuccessStatusCode();
    byte[] responseData = await response.Content.ReadAsByteArrayAsync();

    File.WriteAllBytes("test.png", responseData);
}

【讨论】:

    猜你喜欢
    • 2013-08-27
    • 2014-10-14
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    相关资源
    最近更新 更多