I am working on a project where I want to be able to display a QR Code on the screen to the user.
I'm using the QR Code generate from http://qrcodenet.codeplex.com/ which is working fine but I've only found a way to write the QR Code to a file which is now what I want.
Instead, I want the image to be displayed in a control on the WPF window but I don't want to create the file and then set the source of the image to an image control of the newly created file. This seems like a bit of overkill so I'm hoping there is way I can put the stream straight into an image control instead of into a file.
Below is the code that I have so far.
private void generateQRCode()
{
QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
QrCode qrCode;
encoder.TryEncode("Test", out qrCode);
DrawingBrushRenderer dRenderer = new DrawingBrushRenderer(
new FixedModuleSize(2, QuietZoneModules.Two), System.Windows.Media.Brushes.Black,
System.Windows.Media.Brushes.White);
DrawingBrush dBrush = dRenderer.DrawBrush(qrCode.Matrix);
System.Windows.Shapes.Rectangle rect = new System.Windows.Shapes.Rectangle();
rect.Width = 150;
rect.Height = 150;
rect.Fill = dBrush;
MemoryStream ms = new MemoryStream();
dRenderer.WriteToStream(qrCode.Matrix, ImageFormatEnum.PNG, ms, new System.Windows.Point(96, 96));
var image = new System.Drawing.Bitmap(System.Drawing.Image.FromStream(ms), new System.Drawing.Size(new System.Drawing.Point(200, 200)));
image.Save("myImage.png", System.Drawing.Imaging.ImageFormat.Png);
}
Basically, I want to replace the image.save()
function so that the image is instead show directly in a control on my apps GUI, not written to a separate file.
I've actually never written anything in WPF, so this could be wrong, but you probably want to do something like this. I'll copy the answer from that question below:
using(MemoryStream memory = new MemoryStream())
{
image.Save(memory, ImageFormat.Png);
memory.Position = 0;
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
Then, I assume, you can associate that BitmapImage with whatever control you use to display the image.