在Windows商店应用项目中我有这个方法
private async void getUSerImage()
{
try
{
using (var httpClient = new HttpClient { BaseAddress = Constants.baseAddress })
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", App.Current.Resources["token"] as string);
using (var response = await httpClient.GetAsync("user/image"))
{
string responseData = await response.Content.ReadAsStringAsync();
byte[] bytes = Encoding.Unicode.GetBytes(responseData);
StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("userImage.jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sampleFile, bytes);
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
我试图将收到的二进制数据转换为字节并将其另存为文件 这就是responseData包含的内容:
图像被创建但是它已损坏,我无法打开它我假设这个
byte[] bytes = Encoding.Unicode.GetBytes(responseData);
无效
webservice文档说"正文包含二进制图像数据" 有没有更好的方法将接收的二进制数据转换为字节并将其保存到文件?
修改
我最终做到了这一点并且有效
Stream imageStream = await response.Content.ReadAsStreamAsync();
byte[] bytes = new byte[imageStream.Length];
imageStream.Read(bytes, 0, (int)imageStream.Length);
StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("userImage.jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sampleFile, bytes);
var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
答案 0 :(得分:2)
您希望首先将数据读入流中,而不是将其作为字符串读取:
Stream imageStream= await response.Content.GetStreamAsync(theURI);
var image = System.Drawing.Image.FromStream(imageStream);
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
答案 1 :(得分:0)
试试这个
context.Response.ContentType = "image/jpeg";
// Get the stream
var image = System.Drawing.Image.FromStream(stream);
image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
如果要显示图像而不是保存可以使用
$('img')[0].src = 'Home/getUSerImage' // what ever image url