如何在winui3应用程序中显示位图对象



我想在WinUI 3桌面应用程序中显示QRCoder库(https://github.com/codebude/QRCoder/)生成的QR码。

从QRCoder我得到System.Drawing.Bitmap对象:

QRCodeGenerator qrCodeGenerator = new();
QRCodeData qrCodeData = qrCodeGenerator.CreateQrCode(associateSoftwareTokenResponse.SecretCode, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new(qrCodeData);
Bitmap qrCodeBitmap = qrCode.GetGraphic(20);

然后赋值给XAMLImagecontrol:qrCodeImage.Source = qrCodeBitmap给出错误:

错误CS0029不能隐式转换类型"System.Drawing"。位图"Microsoft.UI.Xaml.Media.ImageSource">

显然还需要一些转换。

我设法找到的所有文档和示例都解释了如何从文件中打印图像,但不是位图对象。

我如何在我的winui3应用程序中显示这个代码生成的位图?

您应该能够从流中创建一个BitmapImage,如下所示:

Bitmap qrCodeBitmap = ...;
BitmapImage bitmapImage = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
qrCodeBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Position = 0;
bitmapImage.SetSource(stream.AsRandomAccessStream());
}
image.Source = bitmapImage;

最新更新