用上篇的方法生成的二维码有个小问题,边框太大,网上说构造函数里的”Margin”指定为1就可以,试过后没用,查到别人写的去除边框的代码,就是手动操作去除周边的空白,不过是Java版的,这里给出c#版的
======================继续给自己new对象的分割线============
修改上篇文章里的CreateQRbmp()函数,并添加DeleteWhite()函数
/// <summary>
/// 生成二维码
/// </summary>
/// <param name="content">需要生成二维码的内容</param>
/// <param name="size">二维码图片长宽大小</param>
/// <returns></returns>
public static Bitmap CreateQRbmp(string content, int size)
{
try
{
var options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = size,
Height = size,
Margin = 1,
ErrorCorrection = ZXing.QrCode.Internal.ErrorCorrectionLevel.H
};
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = options;
BitMatrix matrix = writer.Encode(content);
matrix = DeleteWhite(matrix);//删除白边
int width = matrix.Width;
int height = matrix.Height;
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (matrix[x, y])
{
bitmap.SetPixel(x, y, Color.Black);
}
else
{
bitmap.SetPixel(x, y, Color.White);
}
}
}
//bitmap.Save("qr.png");
return bitmap;
}
catch (Exception ex)
{
return null;
}
}
private static BitMatrix DeleteWhite(BitMatrix matrix)
{
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++)
{
for (int j = 0; j < resHeight; j++)
{
if (matrix[i + rec[0], j + rec[1]])
resMatrix[i, j] = true;
}
}
return resMatrix;
}