Save image as Base64 string
Is it possible to save QRCode as base64 string
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?
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
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:
-
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.CommonandSystem.Drawing.Primitives. Additionally, copy and add QrCodeBitmapExtensions.cs -
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");