首页 > 代码库 > 引用ZXing生成二维码

引用ZXing生成二维码

1、生成二维码

ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。

Zxing可以实现使用手机的内置的摄像头完成条形码的扫描及解码。本文引用zxing.dll,生成二维码。

技术分享
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;
using System.IO;
using System.Collections;


private void btnGenerate_Click(object sender, EventArgs e)
        {
            ByteMatrix byteMatrix;
            string content = this.textBox1.Text;

            if (!string.IsNullOrEmpty(content))
            {
                byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 300, 300);
                bitmap = ToBitmap(byteMatrix);
            }

            this.pictureBox1.Image = bitmap;
            mapCreate = bitmap;
        }

        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;
        }
View Code

2、加图片水印

技术分享
//图片水印处理方法
        private Bitmap ImageWatermark(Bitmap map, string waterpath)
        {
            Image waterimg = Image.FromFile(waterpath);

            //添加水印
            Graphics g = Graphics.FromImage(map);

            //获取水印位置设置
            ArrayList loca = new ArrayList();
            int x = 0;
            int y = 0;
            x = map.Width / 2 - waterimg.Width / 2;
            y = map.Height / 2 - waterimg.Height / 2;
            loca.Add(x);
            loca.Add(y);

            //g.DrawImage(waterimg, new Rectangle(int.Parse(loca[0].ToString()), int.Parse(loca[1].ToString()), waterimg.Width, waterimg.Height));
            g.DrawImage(waterimg, new Rectangle(int.Parse(loca[0].ToString()), int.Parse(loca[1].ToString()), 75, 75));

            return map;
        }
View Code

3、导出

技术分享
//先添加 saveFileDialog控件 

private void btnOut_Click(object sender, EventArgs e)
        {
            try
            {
                saveFileDialog1.ShowDialog();
                string fileName = saveFileDialog1.FileName;

                if (fileName != null)
                {
                    mapCreate.Save(fileName);//mapCreate是bitmap格式的图片
                }
            }
            catch (Exception ex)
            {                
                throw;
            }
        }
View Code

 

引用ZXing生成二维码