问题描述
我只想从互联网URL获取BitmapImage,但是我的函数没有似乎工作正常,只能让我看到一小部分形象。我知道WebResponse正在工作异步,这当然是为什么我有这个问题,但是如何同步执行?
这是我的功能:
内部静态BitmapImage GetImageFromUrl(string url)
{
Uri urlUri = new Uri(url);
WebRequest webRequest = WebRequest.CreateDefault(urlUri);
webRequest.ContentType =image / jpeg;
WebResponse webResponse = webRequest.GetResponse();
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = webResponse.GetResponseStream();
image.EndInit();
返回图片;
}
非常感谢您的帮助。
首先,你应该只是下载图像,并将其存储在临时文件或 MemoryStream
中。然后从中创建 BitmapImage
对象。
您可以下载图像,例如:
Uri urlUri = new Uri(url);
var request = WebRequest.CreateDefault(urlUri);
byte [] buffer = new byte [4096];
使用(var target = new FileStream(targetFileName,FileMode.Create,FileAccess.Write))
{
using(var response = request.GetResponse())
{
using(var stream = response.GetResponseStream())
{
int read;
while((read = stream.Read(buffer,0,buffer.Length))> 0)
{
target.Write(buffer,0,read);
}
}
}
}
I am trying to do a simple thing but I can't ...
I just want to get a BitmapImage from a internet URL, but my function doesn't seem to work properly, it only return me a small part of the image. I know WebResponse are working async and that's certainly why I have this problem, but how can I do it synchronously ?
Here is my function :
internal static BitmapImage GetImageFromUrl(string url)
{
Uri urlUri = new Uri(url);
WebRequest webRequest = WebRequest.CreateDefault(urlUri);
webRequest.ContentType = "image/jpeg";
WebResponse webResponse = webRequest.GetResponse();
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = webResponse.GetResponseStream();
image.EndInit();
return image;
}
Thank a lot for your help.
First you should just download the image, and store it locally in a temporary file or in a MemoryStream
. And then create the BitmapImage
object from it.
You can download the image for example like this:
Uri urlUri = new Uri(url);
var request = WebRequest.CreateDefault(urlUri);
byte[] buffer = new byte[4096];
using (var target = new FileStream(targetFileName, FileMode.Create, FileAccess.Write))
{
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
target.Write(buffer, 0, read);
}
}
}
}
这篇关于从URL同步下载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!