天天看點

C# 二維碼 生成、解析

網頁生成二維碼:

http://scimence.gitee.io/url/QRTool.html?待生成二維碼的資料

二維碼工具。生成、解析二維碼。

C# 二維碼 生成、解析

使用方法:

1. 拖動任意二維碼圖像至工具,即可自動解析

2. 輸入二維碼連結位址,自動生成二維碼圖像。右鍵->儲存。

工具下載下傳

工具源碼下載下傳

工具核心源碼:

C# 二維碼 生成、解析
C# 二維碼 生成、解析
C# 二維碼 生成、解析
//生成二維碼:
Bitmap pic = QRTool.Form_QR.ToQR("url"); 	// 生成二維碼
QRTool.Form_QR.Save(pic);              		// 儲存圖像

//解析二維碼:
String url = QRTool.ToCode(pic);
           
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yc.QrCodeLib;
using Yc.QrCodeLib.Data;

namespace QRTool
{
    public partial class Form_QR : Form
    {
        public Form_QR()
        {
            InitializeComponent();
        }


        #region Form_QR相關事件邏輯

        bool update = true;
        /// <summary>
        /// url位址變動,更新二維碼顯示
        /// </summary>
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (update)
            {
                String url = textBox1.Text;
                if (!url.Equals(""))
                {
                    Bitmap pic = ToQR(url);
                    pictureBox1.Image = pic;
                }
            }
        }

        private void panel1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))    //判斷拖來的是否是檔案  
                e.Effect = DragDropEffects.Link;                //是則将拖動源中的資料連接配接到控件  
            else e.Effect = DragDropEffects.None;
        }

        /// <summary>
        /// 二維碼圖像變動,解析url位址到輸入框
        /// </summary>
        private void panel1_DragDrop(object sender, DragEventArgs e)
        {
            Array files = (System.Array)e.Data.GetData(DataFormats.FileDrop);//将拖來的資料轉化為數組存儲
            foreach (object I in files)
            {
                try
                {
                    string str = I.ToString();
                    Image pic = Bitmap.FromFile(str);
                    pictureBox1.Image = pic;

                    // 解析二維碼圖像
                    update = false;
                    String code = ToCode(new Bitmap(pic));
                    textBox1.Text = code;
                    update = true;

                    break;
                }
                catch (Exception ex) { }
            }
        }

        /// <summary>
        /// 儲存圖像
        /// </summary>
        private void 儲存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            linkLabel1.Visible = true;
            if (pictureBox1.Image != null)
            {
                Bitmap pic = new Bitmap(pictureBox1.Image);

                String filepath = Save(pic);
                linkLabel1.Text = "二維碼已儲存:" + filepath;
            }
            else linkLabel1.Text = "";
        }

        /// <summary>
        /// 在檔案浏覽器中顯示已儲存的二維碼圖像檔案
        /// </summary>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            String dir = curDir() + "QR\\";
            String name = linkLabel1.Text.Substring("二維碼已儲存:".Length);
            ShowFileInExplorer(dir + name);

            linkLabel1.Visible = false;
        }

        private void 跳轉二維碼位址ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!textBox1.Text.Equals("")) System.Diagnostics.Process.Start(textBox1.Text);
        }

        #endregion


        #region 二維碼功能函數

        /// <summary>
        /// 擷取連結位址對應的二維碼圖像
        /// </summary>
        public static Bitmap ToQR(String url)
        {
            QrEncoder qrEncoder = new QrEncoder(ErrorCorrectionLevel.M);
            QrCode qrCode = qrEncoder.Encode(url);

            GraphicsRenderer render = new GraphicsRenderer(new FixedModuleSize(5, QuietZoneModules.Two), Brushes.Black, Brushes.White);
            DrawingSize size = render.SizeCalculator.GetSize(qrCode.Matrix.Width);
            Bitmap pic = new Bitmap(size.CodeWidth, size.CodeWidth);
            Graphics g = Graphics.FromImage(pic);

            render.Draw(g, qrCode.Matrix);

            return pic;
        }

        /// <summary>
        /// 将二維碼圖像轉化為編碼串
        /// </summary>
        public static string ToCode(Bitmap pic)
        {
            QRCodeDecoder decoder = new QRCodeDecoder();
            String decodedString = decoder.decode(new QRCodeBitmapImage(pic));

            return decodedString;
        }

        # endregion


        #region 其他相關功能函數

        /// <summary>
        /// 儲存圖像傳回檔案名
        /// </summary>
        public static String Save(Bitmap pic)
        {
            String path = curDir() + "QR\\";
            checkDir(path);

            String name = DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".png";
            Save(pic, path + name);

            return name;
        }

        /// <summary>
        /// 儲存圖像
        /// </summary>
        public static void Save(Bitmap pic, String filePath)
        {
            if (File.Exists(filePath)) File.Delete(filePath);
            pic.Save(filePath, ImageFormat.Png);
        }

        /// <summary>
        /// 擷取目前運作路徑
        /// </summary>
        public static string curDir()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        /// <summary>
        /// 檢測目錄是否存在,若不存在則建立
        /// </summary>
        public static void checkDir(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
        }

        /// <summary>
        /// 在檔案浏覽器中顯示指定的檔案
        /// </summary>
        public static void ShowFileInExplorer(String file)
        {
            if (File.Exists(file)) System.Diagnostics.Process.Start("explorer.exe", "/e,/select, " + file);
            else System.Diagnostics.Process.Start("explorer.exe", "/e, " + file);
        }

        #endregion


    }
}
           

繼續閱讀