c# - 如何在远程服务器上使用 BitmapImage 设置 UriSource?

标签 c# .net 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;

相同的代码和相同的图像,但 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/

相关文章:

c# - 当我只有“继承表单”选项时,如何将表单添加到我的 Windows 窗体项目?

c# - 如何制作像 Popcorn Time 这样的 GUI?

.net - "RdlCompile"找不到任务

.Net 与 SSIS : What should SSIS be used for?

javascript - 跨源请求被阻止 : Occur even after CORS enabled on my API ;

c# - CRM 2011 使用 ICodeWriterFilterService 生成的代码无法构建

c# - 动态添加超链接到 RichTextBox

c# - 如何在长时间运行的 *UI* 操作中让 UI 刷新

wpf - 如何在单独的线程上创建和显示 WPF 窗口?

c# - 为什么'Weiss'='Weiß'或通过Unicode列在SQL Server中搜索