1. 程式人生 > >二維碼圖片轉base64格式給前端顯示

二維碼圖片轉base64格式給前端顯示

二維碼圖片轉base64 格式給前端顯示

<img id="QrCode" src="data:image/jgp;base64,@ViewBag.Qrcodurl" />

                //初始化二維碼生成工具
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                qrCodeEncoder.QRCodeVersion = 0;
                qrCodeEncoder.QRCodeScale = 4;
                //將字串生成二維碼圖片

                Bitmap image = qrCodeEncoder.Encode("字串", Encoding.Default);

                string strbaser64 = "";

                try
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                        byte[] arr = new byte[ms.Length];
                        ms.Position = 0;
                        ms.Read(arr, 0, (int)ms.Length);
                        ms.Close();
    
                    strbaser64 = Convert.ToBase64String(arr);
                    }
                }
                catch (Exception)
                {
                    throw new Exception("Something wrong during convert!");
                }