1
Vote

Can't create Qr Code as a image file

description

Hi all,

I am trying to generate a QR code image (png or jpeg) for any given string and save it to a file in my local system. I am using VS 2015 and .net framework 4.5
I have include the Gma.QrCodeNet.Encoding.Net45.dll in my project

As the example given in here I am trying to create a QR code.
https://qrcodenet.codeplex.com/wikipage?title=GraphicsRenderer&referringTitle=Renderer

I wrote a button click function to create QR Code

private void button1_Click(object sender, EventArgs e)
    {
        QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
        QrCode qrCode;
        encoder.TryEncode("Test", out qrCode);

        GraphicsRenderer gRenderer = new GraphicsRenderer(
            new FixedModuleSize(2, QuietZoneModules.Two),
            Brushes.Black, Brushes.White);
        MemoryStream ms = new MemoryStream();
        gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, ms);

        using (FileStream file = new FileStream("C:/Users/vxt/Desktop/test.png", FileMode.Create, System.IO.FileAccess.Write))
        {
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, (int)ms.Length);
            file.Write(bytes, 0, bytes.Length);
            ms.Close();
        }

        GraphicsRenderer tRend = new GraphicsRenderer(new FixedCodeSize(200, QuietZoneModules.Two), Brushes.Black, Brushes.White);
        MemoryStream ms1 = new MemoryStream();
        tRend.WriteToStream(qrCode.Matrix, ImageFormat.Jpeg, ms1);

        using (FileStream file1 = new FileStream("C:/Users/vxt/Desktop/test1.jpeg", FileMode.Create, System.IO.FileAccess.Write))
        {
            byte[] bytes = new byte[ms1.Length];
            ms1.Read(bytes, 0, (int)ms1.Length);
            file1.Write(bytes, 0, bytes.Length);
            ms1.Close();
        }

    }
Files are created but when I open its says file either too large or corrupted. i checked the file size in properties it is just 4KB.
Can any of you tell me what am I doing wrong

comments

venutamizh wrote Nov 25, 2016 at 5:03 AM

I figured it out my self. instead of using a memory stream and copying to a file stream we can use a file stream directly

Something like this.
QrEncoder encoder = new QrEncoder(ErrorCorrectionLevel.M);
        QrCode qrCode;
        encoder.TryEncode("Test", out qrCode);

        GraphicsRenderer gRenderer = new GraphicsRenderer(
            new FixedModuleSize(2, QuietZoneModules.Two),
            Brushes.Black, Brushes.White);
        MemoryStream ms = new MemoryStream();
        FileStream file = new FileStream("C:/Users/vxt/Desktop/test.png", FileMode.Create, System.IO.FileAccess.Write);
        gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, file);