how to create a qrcode?

mc 5,426 Reputation points
2023-06-05T02:02:16.6666667+00:00

how to create qrCode with url into a stream in api?

Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Chen Li - MSFT 1,231 Reputation points
    2023-06-05T07:25:14.74+00:00

    Hi @mc,

    This may be what you want.

    First, install QRCode Nuget Package:

    User's image

    Controller and Extension:

    [Route("api/[controller]")]
    [ApiController]
    public class QrcodeController : ControllerBase
    {
        [HttpPost]
        public string CreateQRCode(string qRCode)
        {
            QRCodeGenerator QrGenerator = new QRCodeGenerator();
            QRCodeData QrCodeInfo = QrGenerator.CreateQrCode(qRCode, QRCodeGenerator.ECCLevel.Q);
            QRCode QrCode = new QRCode(QrCodeInfo);
    
            //save qrr file to wwwroot/qrr folder
            //string fileGuid = Guid.NewGuid().ToString().Substring(0, 4);
            //QrCodeInfo.SaveRawData("wwwroot/qrr/file-" + fileGuid + ".qrr", QRCodeData.Compression.Uncompressed);
            Bitmap QrBitmap = QrCode.GetGraphic(60);
            byte[] BitmapArray = QrBitmap.BitmapToByteArray();
            string QrUri = string.Format("data:image/png;base64,{0}", Convert.ToBase64String(BitmapArray));
            //ViewBag.QrCodeUri = QrUri;
            return QrUri;
        }
    }
    
    public static class BitmapExtension
    {
        public static byte[] BitmapToByteArray(this Bitmap bitmap)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                bitmap.Save(ms, ImageFormat.Png);
                return ms.ToArray();
            }
        }
    }
    

    If you want to load the QR code after calling this api, the string QrUri output by this api is the src of the img tag.

    For more details, you can check this GitHub Respositiory.


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    Chen Li

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.