C# QRCode自定義二維碼大小
阿新 • • 發佈:2018-11-08
當設定了QRCodeVersion=0之後,二維碼的大小會根據文字內容改變,但是更多時候希望二維碼的大小由引數指定,通過設定QRCodeScale也可以一定程度上改變大小,不過有個精度問題,我測試了下每降一級大概減少49px,而需求是自定義大小。解決辦法,自己寫Graphics來渲染
/// <summary>
/// 生成二維碼
/// </summary>
/// <param name="Content">內容文字</param>
/// <param name="size">圖片尺寸(畫素)</param>
/// <param name="margin"> 圖片白邊(畫素)</param>
/// <returns></returns>
public static Bitmap CreateQRCode(string Content, int size, int margin = 5)
{
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
qrCodeEncoder.QRCodeScale = 5 ;
qrCodeEncoder.QRCodeVersion = 0;
try
{
System.Drawing.Image image = qrCodeEncoder.Encode(Content);
int resWidth = size + 2 * margin;
int resHeight = size + 2 * margin;
// 核心就是這裡新建一個bitmap物件然後將image在這裡渲染
Bitmap newBit = new Bitmap(resWidth, resHeight, PixelFormat.Format32bppRgb);
Graphics gg = Graphics.FromImage(newBit);
// 設定背景白色
for (int y = 0; y < resWidth; y++)
{
for (int x = 0; x < resHeight; x++)
{
newBit.SetPixel(x, y, Color.White);
}
}
// 設定黑色邊框
for (int i = 0; i < resWidth; i++)
{
newBit.SetPixel(i, 0, Color.Black);
newBit.SetPixel(i, resWidth - 1, Color.Black);
}
for (int j = 0; j < resHeight; j++)
{
newBit.SetPixel(0, j, Color.Black);
newBit.SetPixel(resHeight - 1, j, Color.Black);
}
gg.DrawImage(image, margin, margin, size, size);
//newBit.Save(size.ToString() + ".png");
return newBit;
}
catch(Exception ex)
{
return null;
}
}