Home > database >  How to display Bitmap object in WinUI 3 application
How to display Bitmap object in WinUI 3 application

Time:06-08

I want to display QR code generated by QRCoder library ( https://github.com/codebude/QRCoder/ ) in my WinUI 3 desktop app.

From QRCoder I get 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:

Error CS0029 Cannot implicitly convert type 'System.Drawing.Bitmap' to '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.

How can I display this code generated Bitmap in my WinUI 3 app?

CodePudding user response:

You should be able to create a BitmapImage from a stream something like this:

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;
  • Related