使用zxing類生成一維碼、二維碼實例
條形碼在生活中使用的已經相當廣泛了,不管是去書店買書,還是去超市買商品,都會用到條碼,而且每一個條碼中的信息都不盡相同,每一類的商品都有統一的條 碼,當然條碼的類型也有不同,比如有標準的UPC條碼,也有Code39,Code128,EAN8等等好多好多。這些根據不同的需要而被廣泛使用。
最近根據項目的需求,用了一段時間對一維碼、二維碼進行了小小的研究,在一篇Blog中看到使用了google的zxing生成二維碼,好奇之下自己做了一個小Demo。
生成一維碼
生成二維碼
#region 引用程序集
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using com.google.zxing.qrcode;
using com.google.zxing;
using com.google.zxing.common;
using ByteMatrix = com.google.zxing.common.ByteMatrix;
using EAN13Writer = com.google.zxing.oned.EAN13Writer;
using EAN8Writer = com.google.zxing.oned.EAN8Writer;
using MultiFormatWriter = com.google.zxing.MultiFormatWriter;endregion
namespace qr
{
public partial class Form1 : Form
{
public Form1()
{
// 初始化組件
InitializeComponent();
}// public static void writeToFile(ByteMatrix matrix, System.Drawing.Imaging.ImageFormat format, string file) //{ // Bitmap bmap = toBitmap(matrix); // bmap.Save(file, format); //} /// <summary> /// 繪制一維碼、二維碼位圖 /// </summary> /// <param name="matrix"></param> /// <returns></returns> public static Bitmap toBitmap(ByteMatrix matrix) { // 定義位圖的款和高 int width = matrix.Width; int height = matrix.Height; Bitmap bmap = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bmap.SetPixel(x, y, matrix.get_Renamed(x, y) != -1 ? ColorTranslator.FromHtml("0xFF000000") : ColorTranslator.FromHtml("0xFFFFFFFF")); } } return bmap; } private void button1_Click_1(object sender, EventArgs e) { string content = textBox1.Text; int codeWidth = Convert.ToInt16(txtWidth.Text.Trim().ToString()); int codeHeight = Convert.ToInt16(txtHeight.Text.Trim().ToString()); // 生成二維碼 ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, codeWidth, codeHeight); Bitmap bitmap = toBitmap(byteMatrix); pictureBox1.Image = bitmap; //writeToFile(byteMatrix, System.Drawing.Imaging.ImageFormat.Png, sFD.FileName); //SaveFileDialog sFD = new SaveFileDialog(); //sFD.DefaultExt = "*.png|*.png"; //sFD.AddExtension = true; //try //{ // if (sFD.ShowDialog() == DialogResult.OK) // { // } //} //catch (Exception ex) //{ // MessageBox.Show(ex.Message); //} } private void button2_Click(object sender, EventArgs e) { string content = textBox1.Text; // 生成一維碼 ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.EAN_8, 200, 100); Bitmap bitmap = toBitmap(byteMatrix); pictureBox1.Image = bitmap; //Bitmap twobitmap = new Bitmap(bitmap.Width ,bitmap.Height); //Graphics g = Graphics.FromImage(bitmap); //g.DrawString(content, Font, Brushes.Black, pictureBox1.); //pictureBox1.Image = bitmap; } }
} </pre>
來自:http://blog.csdn.net/happylee6688/article/details/8446203
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!