asp.net中利用QRCode生成二维码代码

作者:袖梨 2022-06-25

1、使用下面代码首先需要下载QRCode.DLL文件引用到你的项目中

 代码如下 复制代码

//生成二维码代码
public string generateQRCode()
{
    //生成二维码
    string filename = string.Empty;
    string filepath = string.Empty;
 
    string txt_qr = "需要生成二维码信息";
    string qrEncoding = "Byte";
    string Level = "M";
    string txt_ver = "7";
    string txt_size = "4";
 
    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
    String encoding = qrEncoding;
    if (encoding == "Byte")
    {
        qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
    }
    else if (encoding == "AlphaNumeric")
    {
        qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
    }
    else if (encoding == "Numeric")
    {
        qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
    }
    try
    {
        int scale = Convert.ToInt16(txt_size);
        qrCodeEncoder.QRCodeScale = scale;
    }
    catch (Exception ex)
    {
        return "";
    }
    try
    {
        int version = Convert.ToInt16(txt_ver);
        qrCodeEncoder.QRCodeVersion = version;
    }
    catch (Exception ex)
    {
        return "";
    }
    string errorCorrect = Level;
    if (errorCorrect == "L")
        qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
    else if (errorCorrect == "M")
        qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
    else if (errorCorrect == "Q")
        qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
    else if (errorCorrect == "H")
        qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
 
    Image image;
    String data = txt_qr;
    image = qrCodeEncoder.Encode(data);
    filename = Guid.NewGuid().ToString() + ".jpg";
    filepath = "二维码图片存放路径" + filename;
    System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
    image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
    fs.Close();
    image.Dispose();
    return filepath;
}

相关文章

精彩推荐