简体   繁体   English

如何在 WinUI 3 应用程序中显示 Bitmap object

[英]How to display Bitmap object in WinUI 3 application

I want to display QR code generated by QRCoder library ( https://github.com/codebude/QRCoder/ ) in my WinUI 3 desktop app.我想在我的 WinUI 3 桌面应用程序中显示由 QRCoder 库 ( https://github.com/codebude/QRCoder/ ) 生成的二维码。

From QRCoder I get System.Drawing.Bitmap object:从 QRCoder 我得到System.Drawing.Bitmap object:

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

Then assigning it to XAML Image control: qrCodeImage.Source = qrCodeBitmap gives an error:然后将其分配给 XAML图像控制: qrCodeImage.Source = qrCodeBitmap给出错误:

Error CS0029 Cannot implicitly convert type 'System.Drawing.Bitmap' to 'Microsoft.UI.Xaml.Media.ImageSource'错误 CS0029 无法将类型“System.Drawing.Bitmap”隐式转换为“Microsoft.UI.Xaml.Media.ImageSource”

So apparently there is still some conversion needed.所以显然仍然需要一些转换。

All documentation and examples I managed to find explain how to print an image from file but not Bitmap object.我设法找到的所有文档和示例都解释了如何从文件中打印图像,而不是 Bitmap object。

How can I display this code generated Bitmap in my WinUI 3 app?如何在我的 WinUI 3 应用程序中显示此代码生成的 Bitmap?

You should be able to create a BitmapImage from a stream something like this:您应该能够从这样的流中创建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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM