QrCodeGenerator icon indicating copy to clipboard operation
QrCodeGenerator copied to clipboard

Save image as Base64 string

Open RenMen opened this issue 11 months ago • 3 comments

Is it possible to save QRCode as base64 string

RenMen avatar Apr 17 '25 11:04 RenMen

Base-64 is an encoding. What do you want to encode? A PNG image of the QR code? Or a SVG? How will the resulting Base-64 string be used?

manuelbl avatar Apr 17 '25 13:04 manuelbl

Base-64 is an encoding. What do you want to encode? A PNG image of the QR code? Or a SVG? How will the resulting Base-64 string be used? encoding png of the qrcode will do(eg: QrCode.EncodeBase64String(vcard.Serialize(), QrCode.Ecc.Medium)). I want to create an api to return the encoded string. I need to use it in html image source

RenMen avatar Apr 21 '25 08:04 RenMen

Since you want to use the encoded image in a HTML img tag, I assume you want to create a Data URL.

There are two steps:

  1. Since you want to create a PNG image and .NET does not have a standard pixel graphics library supporting all versions and platforms, you have to pick one for your platform. If you are on Windows, you can go with System.Drawing. Add the NuGet packages System.Drawing.Common and System.Drawing.Primitives. Additionally, copy and add QrCodeBitmapExtensions.cs

  2. Use the below code to generate the data URL. This example just uses a simple text. But it can be easily extended for vCard.

string BytesToDataUrl(byte[] image, string mediaType)
{
    return "data:" + mediaType + ";base64," + Convert.ToBase64String(image);
}

var pngBytes = QrCode.EncodeText("Test text", QrCode.Ecc.Medium).ToPng(4, 1);
var dataUrl = BytesToDataUrl(pngBytes , "image/png");

manuelbl avatar Apr 21 '25 10:04 manuelbl