登录
原创

名片识别示例代码

专栏C#
发布于 2020-09-30 阅读 790
  • C#
原创
本程序适用于聚合名片识别接口:http://www.juhe.cn/docs/api/id/139

注:项目中如遇无法引用 System.Web.dll 问题,修改“项目属性”-“应用程序”-“目标框架” ,由“.NET framework 4 Client Profile”修改为“.NET framework 4”。然后再引用 .NET 4.0 的 System.Web.dll 即可

前端界面代码:
namespace mingpianshibie
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.open = new System.Windows.Forms.Button();
            this.pixel = new System.Windows.Forms.Button();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.ImgTobase64 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.label1 = new System.Windows.Forms.Label();
            this.lb_show = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.groupBox1.SuspendLayout();
            this.SuspendLayout();
            // 
            // open
            // 
            this.open.Location = new System.Drawing.Point(414, 29);
            this.open.Name = "open";
            this.open.Size = new System.Drawing.Size(112, 29);
            this.open.TabIndex = 0;
            this.open.Text = "选择图片";
            this.open.UseVisualstyleBackColor = true;
            this.open.Click += new System.EventHandler(this.open_Click);
            // 
            // pixel
            // 
            this.pixel.Location = new System.Drawing.Point(414, 92);
            this.pixel.Name = "pixel";
            this.pixel.Size = new System.Drawing.Size(112, 29);
            this.pixel.TabIndex = 3;
            this.pixel.Text = "灰度化处理";
            this.pixel.UseVisualstyleBackColor = true;
            this.pixel.Click += new System.EventHandler(this.pixel_Click);
            // 
            // pictureBox2
            // 
            this.pictureBox2.Location = new System.Drawing.Point(6, 141);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(373, 113);
            this.pictureBox2.TabIndex = 5;
            this.pictureBox2.TabStop = false;
            // 
            // pictureBox1
            // 
            this.pictureBox1.Location = new System.Drawing.Point(6, 17);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(373, 110);
            this.pictureBox1.TabIndex = 4;
            this.pictureBox1.TabStop = false;
            // 
            // ImgTobase64
            // 
            this.ImgTobase64.Location = new System.Drawing.Point(414, 153);
            this.ImgTobase64.Name = "ImgTobase64";
            this.ImgTobase64.Size = new System.Drawing.Size(112, 29);
            this.ImgTobase64.TabIndex = 6;
            this.ImgTobase64.Text = "图片base64转换";
            this.ImgTobase64.UseVisualstyleBackColor = true;
            this.ImgTobase64.Click += new System.EventHandler(this.ImgTobase64_Click);
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(414, 216);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(112, 29);
            this.button2.TabIndex = 7;
            this.button2.Text = "名片识别";
            this.button2.UseVisualstyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.button2_Click_1);
            // 
            // groupBox1
            // 
            this.groupBox1.BackColor = System.Drawing.SystemColors.Control;
            this.groupBox1.Controls.Add(this.pictureBox1);
            this.groupBox1.Controls.Add(this.pictureBox2);
            this.groupBox1.Location = new System.Drawing.Point(12, 12);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(396, 260);
            this.groupBox1.TabIndex = 8;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "图片展示";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(16, 299);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(65, 12);
            this.label1.TabIndex = 9;
            this.label1.Text = "识别结果:";
            // 
            // lb_show
            // 
            this.lb_show.Location = new System.Drawing.Point(76, 299);
            this.lb_show.Name = "lb_show";
            this.lb_show.Size = new System.Drawing.Size(332, 28);
            this.lb_show.TabIndex = 10;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(553, 348);
            this.Controls.Add(this.lb_show);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.ImgTobase64);
            this.Controls.Add(this.pixel);
            this.Controls.Add(this.open);
            this.FormBorderstyle = System.Windows.Forms.FormBorderstyle.FixedToolWindow;
            this.Name = "Form1";
            this.Text = "名片识别";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.groupBox1.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button open;
        private System.Windows.Forms.Button pixel;
        private System.Windows.Forms.PictureBox pictureBox2;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Button ImgTobase64;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label lb_show;
    }
}

后端代码:

namespace mingpianshibie
{
    public partial class Form1 : Form
    {
        Bitmap curBitmap;
        Bitmap bitmap;
        String strbaser64;
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 图片转base64
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImgTobase64_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Multiselect = true;
            dlg.title = "选择要转换的图片";
            dlg.Filter = "Image files (*.jpg;*.bmp;*.gif;*.png)|*.jpg*.jpeg;*.gif;*.bmp|AllFiles (*.*)|*.*";
            if (DialogResult.OK == dlg.ShowDialog())
            {
                for (int i = 0; i < dlg.FileNames.Length; i++)
                {
                    ImgToba<x>se64String(dlg.FileNames[i].ToString());
                }
            }
        }

        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void open_Click(ob<x>ject sender, EventArgs e)
        {
            OpenFileDialog opnDlg = new OpenFileDialog();
            opnDlg.Filter = "所有图像文件 | *.bmp; *.pcx; *.png; *.jpg; *.gif;" +
                "*.tif; *.ico; *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf|" +
                "位图( *.bmp; *.jpg; *.png;...) | *.bmp; *.pcx; *.png; *.jpg; *.gif; *.tif; *.ico|" +
                "矢量图( *.wmf; *.eps; *.emf;...) | *.dxf; *.cgm; *.cdr; *.wmf; *.eps; *.emf";
            opnDlg.ti<x>tle = "打开图像文件";
            opnDlg.ShowHelp = true;
            if (opnDlg.ShowDialog() == DialogResult.OK)
            {
                string curFileName = opnDlg.FileName;
                try
                {
                    //使用Image.FromFile创建图像对象
                    curBitmap = (Bitmap)Image.FromFile(curFileName);
                    bitmap = curBitmap;
                    pictureBox1.Image = curBitmap;
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }
            //对窗体进行重新绘制
            Invalidate();
        }

        /// <summary>
        /// 提取灰度法
        /// 为了将位图的颜色设置为灰度或其他颜色,需要使用GetPixel来读取当前像素的颜色--->计算灰度值--->使用SetPixel应用新的颜色
        /// </summary>
        private void pixel_Click(ob<x>ject sender, EventArgs e)
        {
            if (bitmap != null)
            {
                Color curColor;
                int ret;
                //二维图像数组循环  
                for (int i = 0; i < bitmap.Width; i++)
                {
                    for (int j = 0; j < bitmap.Height; j++)
                    {
                        //读取当前像素的RGB颜色值
                        curColor = bitmap.GetPixel(i, j);
                        //利用公式计算灰度值(加权平均法)
                        ret = (int)(curColor.R * 0.299 + curColor.G * 0.587 + curColor.B * 0.114);
                        //设置该点像素的灰度值,R=G=B=ret
                        bitmap.SetPixel(i, j, Color.FromArgb(ret, ret, ret));
                    }
                }
                this.pictureBox2.Image = bitmap;
                //另存灰度处理后的图片
                bitmap.Save(Environment.CurrentDirectory + "//" + System.DateTime.Now.Second.ToString() + ".jpg");
                MessageBox.Show("处理成功!", "消息");
                //对窗体进行重新绘制
                Invalidate();
            }
            else
                MessageBox.Show("请选择图片!", "消息");
        }

        /// <summary>
        /// 图片转为ba<x>se64编码的文本
        /// </summary>
        /// <param name="Imagefilename"></param>
        private void ImgToba<x>se64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);
                this.pictureBox1.Image = bmp;
                //保存图片转ba<x>se64后的txt文件
                FileStream fs = new FileStream(Imagefilename + ".ba<x>se64.txt", FileMode.Create);
                StreamWriter sw = new StreamWriter(fs);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                strba<x>ser64 = Convert.Toba<x>se64String(arr);
                sw.Write(strba<x>ser64);
                sw.Close();
                fs.Close();
                MessageBox.Show("转换成功!", "消息");
            }
            catch (Exception ex)
            {
                MessageBox.Show("ImgToba<x>se64String 转换失败\nException:" + ex.Message);
            }
        }

        /// <summary>
        /// 名片识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click_1(ob<x>ject sender, EventArgs e)
        {
            if (strba<x>ser64 != null)
            {
                //接口地址
                string url = "http://op.juhe.cn/hanvon/bcard/query";
                IDictionary<string, string> Parem = new Dictionary<string, string>();
                //参数image
                Parem.Add("image", strba<x>ser64);
                //参数key
                Parem.Add("key", "60351739eea0f9c496501d93b85602bb");
                //调用post请求
                string result = DoPost(url, Parem);
                lb_show.Text = result;
                MessageBox.Show(result);
                Debug.WriteLine("识别结果:" + result);
            }
            else
                MessageBox.Show("请将图片ba<x>se64处理!", "消息");
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, IDictionary<string, string> parameters)
        {
            HttpWebRequest req = null;
            HttpWebResponse rsp = null;
            System.IO.Stream reqStream = null;
            try
            {
                req = GetWebRequest(url, "POST");
                req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                rsp = (HttpWebResponse)req.GetResponse();
                Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                return GetResponseAsString(rsp, encoding);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                if (reqStream != null) reqStream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        /// <summary>
        /// 创建http或https请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public HttpWebRequest GetWebRequest(string url, string method)
        {
            HttpWebRequest req = null;
            if (url.Contains("https"))
            {   //验证服务器证书回调
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                req = (HttpWebRequest)WebRequest.Create(url);
            }
            req.ServicePoint.Expect100Continue = false;
            req.ServicePoint.ConnectionLimit = 200;
            req.Method = method;
            req.KeepAlive = false;
            req.ProtocolVersion = HttpVersion.Version10;
            req.UserAgent = "Top4Net";
            req.Timeout = 5000;
            return req;
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        public string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        /// <summary>
        /// 回调验证证书问题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        public bool CheckValidationResult(ob<x>ject sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   //总是接受
            return true;
        }
    }
}

评论区

king
4粉丝

励志做一条安静的咸鱼,从此走上人生巅峰。

1

1

2

举报