跳过正文

WPF Image UriSource and Data Binding using http:\\ URL

Tech C# .Net WPF
浮世絵空事
作者
浮世絵空事
所谓灵魂 几行代码

WPF Image UriSource and Data Binding using http:\\ URL

Solution 1

http://stackoverflow.com/questions/3148163/wpf-image-urisource-and-data-binding-using-http-url

var url = @"http://xxx.jpg";
var image = new BitmapImage();
const int bytesToRead = 100;

var request = WebRequest.Create(new Uri(url, UriKind.Absolute));
request.Timeout = -1;
var response = request.GetResponse();
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
    var reader = new BinaryReader(responseStream);
    var memoryStream = new MemoryStream();

    var bytebuffer = new byte[bytesToRead];
    var bytesRead = reader.Read(bytebuffer, 0, bytesToRead);

    while (bytesRead > 0)
    {
        memoryStream.Write(bytebuffer, 0, bytesRead);
        bytesRead = reader.Read(bytebuffer, 0, bytesToRead);
    }

    image.BeginInit();
    memoryStream.Seek(0, SeekOrigin.Begin);

    image.StreamSource = memoryStream;
    image.EndInit();

    ImgAvatar.Source = image;

    bytebuffer = null;
    memoryStream.Dispose();
    memoryStream = null;
}

Solution 2

var url = @"http://xxx.jpg";
var source = new BitmapImage(new Uri(url, UriKind.RelativeOrAbsolute))
{
    CacheOption = BitmapCacheOption.None,
    CreateOptions = BitmapCreateOptions.DelayCreation
};
source.DecodeFailed += (sender, e) =>
{
    ImgAvatar.Visibility = Visibility.Hidden;
    ImgAvatarDefault.Visibility = Visibility.Visible;
};
source.DownloadFailed += (sender, e) =>
{
    ImgAvatar.Visibility = Visibility.Hidden;
    ImgAvatarDefault.Visibility = Visibility.Visible;
};
source.DownloadCompleted += (sender, e) =>
{
    ImgAvatar.Visibility = Visibility.Hidden;
    ImgAvatarDefault.Visibility = Visibility.Visible;
};
ImgAvatar.Source = source;