【问题标题】:how to save response with “ContentType= {image/jpeg}” as image C#?如何将“ContentType= {image/jpeg}”的响应保存为图像 C#?
【发布时间】:2017-05-26 12:53:33
【问题描述】:

我正在使用 Microsoft Graph API 从 Azure Active Directory 获取用户配置文件图像。

查看示例:

我正在使用 C# 控制台应用程序使用此 API 调用。我有以下代码。

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer","MY ACCESS TOKEN");
var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value");
var test = response.Content.ReadAsStringAsync();

现在,这里响应的 Content-Type 是 {image/jpeg}

我得到的数据看起来像属性 Result 来自下图。

当我尝试使用以下代码将此图像保存在本地驱动器上时:

System.IO.File.WriteAllBytes(@"C:\image.bmp", Convert.FromBase64String(test.Result));

它给了我错误:

{System.FormatException: 输入不是有效的 Base-64 字符串,因为它 包含非 base 64 字符、两个以上的填充字符,或 填充字符中的非法字符。在 System.Convert.FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength) 在 System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength) 在 System.Convert.FromBase64String(String s)
在 Microsoft_Graph_Mail_Console_App.MailClient.d__c.MoveNext() 在 d:\Source\MailClient.cs:line 125}

我理解这个错误,因为结果不能转换为 byte[]

所以,我想知道,我可以直接使用Result属性中的数据在我的本地系统上创建和保存图像吗?

【问题讨论】:

    标签: c# image console azure-active-directory microsoft-graph-api


    【解决方案1】:

    对于图像,响应的内容是字节流而不是字符串。 因此,您只需读取响应流并将其复制到输出流。例如:

    HttpResponseMessage response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value");
    using (Stream responseStream = await response.Content.ReadAsStreamAsync())
    {
        using (FileStream fs = new FileStream(@"c:\image.jpg", FileMode.Create))
        {
            // in dotnet 4.5
            await source.CopyToAsync(fs);
        }
    }
    

    如果你是,在dotnet 4.0 中,使用source.CopyTo(fs) 而不是它的异步部分。

    【讨论】:

      猜你喜欢
      • 2014-02-08
      • 1970-01-01
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 1970-01-01
      • 2022-06-30
      相关资源
      最近更新 更多