我需要从 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;
相同的代码和相同的图像,但 UriSource 指向网络服务器,图像不会被打印出来,也不会抛出任何错误。知道我做错了什么吗?
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;
最佳答案
图像可能没有完全下载。打印前,检查 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
};
}
另一种(同步)解决方案是在创建 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
关于c# - 如何在远程服务器上使用 BitmapImage 设置 UriSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21093252/