如何使用BitmapImage设置UriSource与远程服务器?

Gib*_*boK 2 .net c# wpf

我需要从UriSrouce创建一个BitmaImage并打印它(在WPF应用程序中).使用以下代码我可以打印图像:

Image imgVoucher = new Image();
BitmapImage bImgVoucher = new BitmapImage();

bImgVoucher.BeginInit();
bImgVoucher.UriSource = new Uri(@"C:\logo-1.png", UriKind.Absolute); // Print ok
bImgVoucher.EndInit();
imgVoucher.Source = bImgVoucher;
Run Code Online (Sandbox Code Playgroud)

相同的代码和相同的图像,但UriSource指向Web服务器,图像不会打印,也不会引发错误.知道我做错了什么吗?

Image imgVoucher = new Image();
BitmapImage bImgVoucher = new BitmapImage();

bImgVoucher.BeginInit();
bImgVoucher.UriSource = new Uri("http://123123.com/logo.png", UriKind.Absolute); // Does not print
bImgVoucher.EndInit();
imgVoucher.Source = bImgVoucher;
Run Code Online (Sandbox Code Playgroud)

Cle*_*ens 5

可能无法完全下载图像.在打印之前,检查IsDownloading属性并DownloadCompleted根据需要添加事件处理程序:

var bitmap = new BitmapImage(new Uri("http://123123.com/logo.png"));

if (!bitmap.IsDownloading)
{
    // print immediately
}
else
{
    bitmap.DownloadCompleted += (o, e) =>
    {
        // print when download completed
    };
}
Run Code Online (Sandbox Code Playgroud)

另一种(同步)解决方案是在创建BitmapImage之前下载完整的图像数据,例如:

var buffer = new WebClient().DownloadData("http://123123.com/logo.png");
var bitmap = new BitmapImage();

using (var stream = new MemoryStream(buffer))
{
    bitmap.BeginInit();
    bitmap.CacheOption = BitmapCacheOption.OnLoad;
    bitmap.StreamSource = stream;
    bitmap.EndInit();
}

// print now
Run Code Online (Sandbox Code Playgroud)