原文章链接忘记了。。。
1.引用nuget包:Install-Package ThoughtWorks.QRCode
2.可选,如果需要中间带入图片,保存在项目中,在CreateQRCode()方法中传入该图片的相对路径
3.直接调用下面的CreateQRCode方法
该图为带图片实例,图片为内网链接,仅做展示使用
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Web;
using ThoughtWorks.QRCode.Codec;
namespace Common
{
public class QRCodeHelper
{
///
/// 生成二维码
///
/// 扫描后跳转url
/// 中间图片url(相对路径),为空则不带图片
///
public static Bitmap CreateQRCode(string url,string insertImgUrl=null)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCodeEncoder.QRCodeScale = 4;
qrCodeEncoder.QRCodeVersion = 8;
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
Image image = qrCodeEncoder.Encode(url);
if (string.IsNullOrEmpty(insertImgUrl))
{
return AddFrame(image);
}
//插入图片路径
string path = HttpContext.Current.Server.MapPath(insertImgUrl);
var bitmap = AddFrame(CombinImage(image, path), 5);
return bitmap;
}
///
/// 在图片四周加入白边
///
/// 图片
/// 白边的高度,单位是像素
/// Bitmap
private static Bitmap AddFrame(Image Img, int Margin=6)
{
//位图宽高
int width = Img.Width + Margin;
int height = Img.Height + Margin;
Bitmap BitmapResult = new Bitmap(width, height);
Graphics Grp = Graphics.FromImage(BitmapResult);
SolidBrush b = new SolidBrush(Color.White);//这里修改颜色
Grp.FillRectangle(b, 0, 0, width, height);
System.Drawing.Rectangle Rec = new System.Drawing.Rectangle(0, 0, Img.Width, Img.Height);
//向矩形框内填充Img
Grp.DrawImage(Img, Margin/2, Margin/2 , Rec, GraphicsUnit.Pixel);
//返回位图文件
Grp.Dispose();
GC.Collect();
return BitmapResult;
}
///
/// 调用此函数后使此两种图片合并,类似相册,有个
/// 背景图,中间贴自己的目标图片
///
/// 粘贴的源图片
/// 粘贴的目标图片
private static Image CombinImage(Image imgBack, string destImg)
{
Image img = Image.FromFile(destImg); //照片图片
if (img.Height != 65 || img.Width != 65)
{
img = KiResizeImage(img, 65, 65, 0);
}
Graphics g = Graphics.FromImage(imgBack);
g.DrawImage(imgBack, 0, 0, imgBack.Width, imgBack.Height); //g.DrawImage(imgBack, 0, 0, 相框宽, 相框高);
//g.FillRectangle(System.Drawing.Brushes.White, imgBack.Width / 2 - img.Width / 2 - 1, imgBack.Width / 2 - img.Width / 2 - 1,1,1);//相片四周刷一层黑色边框
//g.DrawImage(img, 照片与相框的左边距, 照片与相框的上边距, 照片宽, 照片高);
g.DrawImage(img, imgBack.Width / 2 - img.Width / 2, imgBack.Width / 2 - img.Width / 2, img.Width, img.Height);
GC.Collect();
return imgBack;
}
///
/// Resize图片
///
/// 原始Bitmap
/// 新的宽度
/// 新的高度
/// 保留着,暂时未用
/// 处理以后的图片
private static Image KiResizeImage(Image bmp, int newW, int newH, int Mode)
{
try
{
Image b = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(b);
// 插值算法的质量
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
g.Dispose();
return b;
}
catch
{
return null;
}
}
}
}