代碼如下:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using ThoughtWorks.QRCode.Codec;
using ThoughtWorks.QRCode.Codec.Util;
using System.Web;
namespace DotNet.Utilities
{
public class QRcode
{
/// <summary>
/// 生成二維碼圖片
/// </summary>
/// <param name="str">字符串</param>
/// <param name="size">圖片大小</param>
/// <param name="path">圖片位置
/// 例如 /abc/abc/
/// </param>
/// <returns>返回生成的二維碼圖片路徑</returns>
public string Create(string str, int size, string path)
{
try
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
//設置編碼模式
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
//設置編碼測量度
qrCodeEncoder.QRCodeScale = size;
//設置編碼版本
qrCodeEncoder.QRCodeVersion = 8;
//設置編碼錯誤糾正
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
System.Drawing.Image image = qrCodeEncoder.Encode(str);
string filename = "~" + path + Guid.NewGuid() + ".jpg";
image.Save(HttpContext.Current.Request.MapPath(filename));
return filename.Replace("~", "");
}
catch (Exception)
{
return "";
}
}
/// <summary>
/// 調用此函數後使此兩種圖片合並,類似相冊,有個
/// 背景圖,中間貼自己的目標圖片
/// </summary>
/// <param name="imgBack">粘貼的源圖片</param>
/// <param name="destImg">粘貼的目標圖片</param>
public 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;
}
/// <summary>
/// Resize圖片
/// </summary>
/// <param name="bmp">原始Bitmap</param>
/// <param name="newW">新的寬度</param>
/// <param name="newH">新的高度</param>
/// <param name="Mode">保留著,暫時未用</param>
/// <returns>處理以後的圖片</returns>
public 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;
}
}
}
}
/*
* 引用ThoughtWorks.QRCode.dll
QRcode qrCode = new QRcode();
UserQrCode = qrCode.Create("http://hovertree.com/" , 4, "/Content/Images/QrCode/");
*/