-1

I have qrcode generator (I used ZXing.QrCode)

public Bitmap GenerateQR(int width, int height, string text)
    {
        var bw = new ZXing.BarcodeWriter();
        var encOptions = new ZXing.Common.EncodingOptions() { Width = width, Height = height, Margin = 0 };
        bw.Options = encOptions;
        bw.Format = ZXing.BarcodeFormat.QR_CODE;
        var result = new Bitmap(bw.Write(text));

        return result;
    }

Now I wonted to show qr code in new window so i call:

var window = new Zeszycik.View.show(GenerateQR(300,300,"some txt")); 
window.Show();

But I don't know how to show qrcode in new window

public show(Bitmap qrcode)
    {
        InitializeComponent();
        print(qrcode);
    }
    private void print(Bitmap img)
    {
       image.Source = img; //error
    }
GarryMoveOut
  • 377
  • 5
  • 19
  • The *Write(string)* method of `ZXing.Presentation.BarcodeWriter` will return a `BitmapSource` object which you can directly assign to image.Source. No need to do any Bitmap-->BitmapSource conversion then. (ZXing.Presentation.BarcodeWriter is provided by the *zxing.presentation.dll* assembly which should be part of the ZXing.NET package) –  Jul 26 '14 at 22:03
  • If I do what u say I have an error in `var result = new BitmapSource(bw.Write(text));` _Cannot create an instance of the abstract class or interface 'System.Windows.Media.Imaging.BitmapSource'_ – GarryMoveOut Jul 27 '14 at 11:22
  • I said *ZXing.Presentation.BarcodeWriter.Write(string)* will **return** a BitmapSource object. I did not say that you should do "new BitmapSource(...)". –  Jul 27 '14 at 21:04

1 Answers1

0

Image Source property is of type ImageSource but Bitmap doesn't derive from ImageSource so you need to convert it to an instance of ImageSource which can either be BitmapImage or BitmapSource.

Now, to convert Bitmap to BitmapSource, you can refer to this link here. For sake of completeness of answer I will post the answer from the link here:

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

private BitmapSource Bitmap2BitmapSource(Bitmap bitmap)
{
    IntPtr hBitmap = bitmap.GetHbitMap();
    BitmapSource retval;

    try
    {
        retval = Imaging.CreateBitmapSourceFromHBitmap(
                     hBitmap,
                     IntPtr.Zero,
                     Int32Rect.Empty,
                     BitmapSizeOptions.FromEmptyOptions());
    }
    finally
    {
        DeleteObject(hBitmap); //Necessary to avoid memory leak.
    }

    return retval;
}

Now you can set Image source like this:

image.Source = Bitmap2BitmapSource(img);
Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185