上段时间项目中添加需求,需要将生成报告上显示二维码,让用户可以扫描二维码查看电子内容,网上的方法也比较多,我是通过zxing.dll库来实现的。
简单介绍下,.net平台下编解条形码和二维码的工具,使用非常方便。zxing只是工具而已,是不收费的。
ZXing库的下载地址:http://zxingnet.codeplex.com/
代码如下:
//生成二维码,并将图像保存指定目录
//添加引用zxing.dll后,引用命名空间ZXing、ZXing.Commom、ZXing.QrCode。
public void CreateQRCode()
{
string param = "";//服务器地址,及所带参数
string path = "D:\\TempQRCode\\tempCode";
string filename = path + "\\QRCode.jpg";
try
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
if (File.Exists(filename) && IsFileUsed(filefull) == false)
File.Delete(filename);
BitmapSource result = (BitmapSource)createQRCode(param, 100, 100);
SaveImageToFile(result, filename); //将bitmapsource保存成图像文件
}
catch
{ }
}
[DllImport("gdi32")]
private static extern int DeleteObject(IntPtr o);
private ImageSource createQRCode(string content, int width, int height)
{
BarcodeWriter barcodeWriter = null;
EncodingOptions options = new QrCodeEncodingOptions
{
DisableECI = true,
CharacterSet = "UTF-8",
Width = width,
Height = height,
Margin = 0
};
barcodeWriter = new BarcodeWriter();
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = options;
Bitmap bitmap = barcodeWriter.Write(content);
IntPtr hbitmap = bitmap.GetHbitmap();
BitmapSource result = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hbitmap);
return result;
}
public static bool IsFileUsed(string filename)
{
bool inUse = true;
FileStream fs = null;
try
{
fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.None);
inUse = false;
}
catch
{ }
finally
{
if (fs != null)
{
fs.Close();
}
}
return inUse;
}
private void SaveImageToFile(BitmapSource image, string filePath)
{
BitmapEncoder encoder = GetBitmapEncoder(filePath);
encoder.Frames.Add(BitmapFrame.Create(image));
using (var stream = new FileStream(filePath, FileMode.Create))
{
encoder.Save(stream);
}
}
private BitmapEncoder GetBitmapEncoder(string filePath)
{
var extName = Path.GetExtension(filePath).ToLower();
if (extName.Equals(".bmp"))
{
return new BmpBitmapEncoder();
}
else
{
return new JpegBitmapEncoder();
}
}
这样就生成二维码图片了,并将图片保存到指定路径。