WPF(C#)用字符串生成二维码

用到了google的zxing库,下载地址http://zxingnet.codeplex.com/SourceControl/latest

接下来生成二维码其实就是几行代码可以搞定了。

private void button1_Click(object sender, RoutedEventArgs e)
{
	label1.Content = "";
	try
	{
		//构造二维码写码器
		MultiFormatWriter mutiWriter = new com.google.zxing.MultiFormatWriter();
		ByteMatrix bm = mutiWriter.encode(textBox1.Text, com.google.zxing.BarcodeFormat.QR_CODE, 300, 300);
		Bitmap img = bm.ToBitmap();
		image1.Source = ChangeBitmapToImageSource(img);
	}
	catch (Exception ee)
	{ 
		MessageBox.Show(ee.Message);
	}
}

但是由于WPF的image控件不能直接支持Bitmap,所以需要转换一下

public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
{
	IntPtr hBitmap = bitmap.GetHbitmap();
	ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
	hBitmap,
	IntPtr.Zero,
	Int32Rect.Empty,
	BitmapSizeOptions.FromEmptyOptions());
	return wpfBitmap;
}

QQ截图20141027175540

项目文件:http://pan.baidu.com/s/1c0lcNny     dmgv