#region 二维码
int i = 2;
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnProduct_Click(object sender, EventArgs e)
{
ThoughtWorks.QRCode.Codec.QRCodeEncoder endocder = new ThoughtWorks.QRCode.Codec.QRCodeEncoder();
//二维码背景颜色
endocder.QRCodeBackgroundColor = System.Drawing.Color.White;
//二维码编码方式
endocder.QRCodeEncodeMode = ThoughtWorks.QRCode.Codec.QRCodeEncoder.ENCODE_MODE.BYTE;
//每个小方格的宽度
endocder.QRCodeScale = 4;
//二维码版本号
endocder.QRCodeVersion = 5;//控制版本,不同版本,显示出来的样式不一样
//纠错等级
endocder.QRCodeErrorCorrect = ThoughtWorks.QRCode.Codec.QRCodeEncoder.ERROR_CORRECTION.M;
var person = new { Id = ++i, Name = "wolfy", Gender = 1, Age = 24 + ++i };
//将json川做成二维码
using (Bitmap bitmap = endocder.Encode(new JavaScriptSerializer().Serialize(person), System.Text.Encoding.UTF8))
{
//Bitmap bitmap = endocder.Encode(new JavaScriptSerializer().Serialize(person), System.Text.Encoding.UTF8);
var strSavePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"QRCode{i}.jpg");
strSavePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"QRCode.jpg");
if (!Directory.Exists(Path.GetDirectoryName(strSavePath)))
{
Directory.CreateDirectory(strSavePath);
}
//System.Runtime.InteropServices.ExternalException:
// 使用错误的图像格式保存图像。 - 或 - 图像已保存到同一文件从创建它。出现一般都是保存路经问题,或者aspnet中是读写文件权限问题
bitmap.Save(strSavePath, System.Drawing.Imaging.ImageFormat.Jpeg);
pbxPicture.SizeMode = PictureBoxSizeMode.Zoom;
//pbxQRCode.Image = Bitmap.FromHbitmap(bitmap.GetHbitmap());
//第一种绘图
IntPtr hBitmap = bitmap.GetHbitmap();
pbxQRCode.Image = Bitmap.FromHbitmap(hBitmap);
//pbxQRCode.Image.Save(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"QRCode.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
DeleteObject(hBitmap);
bitmap.Dispose();
//第二种绘图
//Graphics graphics = Graphics.FromImage(bitmap);
//graphics.Clear(Color.White);
再bitmap上绘图
//graphics.DrawImage(new Bitmap(""), new PointF(0, 0));
//graphics.Dispose();
}
//解密二维码
//ThoughtWorks.QRCode.Codec.QRCodeDecoder qRCodeDecoder = new ThoughtWorks.QRCode.Codec.QRCodeDecoder();
//var decoderResult = qRCodeDecoder.decode(new ThoughtWorks.QRCode.Codec.Data.QRCodeBitmapImage(new Bitmap(strSavePath)));
}
/// <summary>
/// 解密二维码
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnConsume_Click(object sender, EventArgs e)
{
var strSavePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"QRCode{i}.jpg");
strSavePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"QRCode.jpg");
ThoughtWorks.QRCode.Codec.QRCodeDecoder qRCodeDecoder = new ThoughtWorks.QRCode.Codec.QRCodeDecoder();
var decoderResult = qRCodeDecoder.decode(new ThoughtWorks.QRCode.Codec.Data.QRCodeBitmapImage(new Bitmap(strSavePath)));
lblTakephotoSavePath.Text = $"二维码:{decoderResult}";
}
#endregion
二维码生成与解析
最新推荐文章于 2022-08-12 11:58:28 发布