简体   繁体   中英

C# - Using ZXing.Net to Create and download SVG QR Code

I am working on a QR Code project and one of the requirements is to be able to download the generated QR Code in SVG format. I was able to display the generated QR Code in PNG format, but I have been trying to download it in SVG format.

I am using XZing library to generate the QR Code in PNG

        Color barcodeColor = System.Drawing.ColorTranslator.FromHtml(colorHex);

        BarcodeWriter barcodeWriter = new BarcodeWriter
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new EncodingOptions
            {
                Width = width,
                Height = height,
                PureBarcode = true
            },
            Renderer = new BitmapRenderer
            {
                Foreground = barcodeColor
            }
        };

        Bitmap barCodeBitmap = barcodeWriter.Write(qrContent);
        var memoryStream = new MemoryStream();

        // save to stream as PNG
        barCodeBitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);

        HttpResponseMessage response = new HttpResponseMessage();
        response.Content = new ByteArrayContent(memoryStream.ToArray());
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        response.StatusCode = HttpStatusCode.OK;

        return response;

I was able to create a BarcodeWriterSvg object but I wasn't able to convert it into a stream and pass it in the header like the PNG

        BarcodeWriterSvg barcodeWriter = new BarcodeWriterSvg
        {
            Format = BarcodeFormat.QR_CODE,
            Options = new EncodingOptions
            {
                Width = width,
                Height = height,
                PureBarcode = true
            },
            Renderer = new SvgRenderer
            {
                Foreground = barcodeColor
            }
        };
        var barCodeBitmap = barcodeWriter.Write(qrContent);
        var memoryStream = new MemoryStream();
        HttpResponseMessage response = new HttpResponseMessage();
        ...

My question is how to be able to convert the object into a stream and pass it in the header? The ultimate goal is to be able to download the file without actually creating a physical copy.

Off the top of my head, and attempting to use the same code paradigm from your example, I would look into something like this:

var barcodeWriter = new BarcodeWriterSvg();
....
....
var svgImage = barcodeWriter.Write(text); //ZXing.Rendering.SvgRenderer.SvgImage
var response = new HttpResponseMessage();
response.Content = new StringContent(svgImage.Content);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/svg+xml");
return response;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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