C#實現拍照並且存水印照片

来源:http://www.cnblogs.com/luoxiaozhao/archive/2016/11/11/6054464.html
-Advertisement-
Play Games

由於一直在高校工作,就涉及到招生工作,招生時候又要收集學生圖像採集,所以就隨手寫了一個圖像採集工具,廢話不多說,進入正題。 圖像採集需要調用攝像頭就行拍照操作,網上查了一下資料,需要引用以下3個dll。 看一下運行界面 界面都比較low,主要是功能實現。 保存照片可以選擇自動覆蓋同名照片或者在照片中 ...


由於一直在高校工作,就涉及到招生工作,招生時候又要收集學生圖像採集,所以就隨手寫了一個圖像採集工具,廢話不多說,進入正題。

圖像採集需要調用攝像頭就行拍照操作,網上查了一下資料,需要引用以下3個dll。

看一下運行界面

界面都比較low,主要是功能實現。

        private void Camera_Load(object sender, EventArgs e)
        {
            this.btnSave.Enabled = false;
            try
            {
                borderSize = GetBorderSize(this);
                captionHeight = GetCaptionHeight(this);
                //InitStudent("", "", "");

                this.comboBox_SizeMode.Text = "填充(保持比例)";
                FilterInfoCollection infos = new FilterInfoCollection(FilterCategory.VideoInputDevice);
                if ((infos != null) && (infos.Count > 0))
                {

                }
                else
                {
                    MessageBox.Show("沒有視頻設備");
                }

                this.LoadVedio();

                this.splitContainer1.Panel2MinSize = 280;
                this.splitContainer1.SplitterDistance = this.splitContainer1.Width - this.splitContainer1.Panel2MinSize + 1;

                mf = new BorderForm();

                mf.Show(this);
                //mf.Left = (this.Left + this.splitContainer1.Panel1.Width - mf.Width) / 2;
                //mf.Top = (this.Top + this.splitContainer1.Panel1.Height - mf.Height) / 2;
                //marLeft = mf.Left - this.Left;
                //marTop = mf.Top - this.Top;

                Rectangle rtPic = this.pictureBox_Camera.RectangleToScreen(this.pictureBox_Camera.ClientRectangle);
                Rectangle rtMF = this.mf.RectangleToScreen(this.mf.ClientRectangle);
                if (rtPic == null || rtMF == null || rtPic.Width == 0 || rtMF.Width == 0)
                {
                    return;
                }
                mf.Left = ((rtMF.Width + rtMF.Left) + (rtPic.Width + rtPic.Left)) / 2;
                mf.Top = ((rtMF.Height + rtMF.Top) + (rtPic.Height + rtPic.Top)) / 2;

                mf.SizeChanged += new EventHandler(mf_SizeChanged);
                mf.LocationChanged += new EventHandler(mf_LocationChanged);

                pictureBox_Camera_SizeChanged(sender, e);

                //啟動連拍
                //this.ShootOneTime = 0;
                this.timer1.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
//載入攝像頭設備
private void LoadVedio()
        {
            FilterInfoCollection infos = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if ((infos != null) && (infos.Count > 0))
            {
                int index = 0;
                foreach (FilterInfo info in infos)
                {
                    this.cmbCaptureDevice.Items.Add(new DeviceInfo(info.Name, info.MonikerString, index, FilterCategory.VideoInputDevice));
                    index++;
                }
                this.cmbCaptureDevice.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 拍照
        /// </summary>
        private void Shoot()
        {
            try
            {
                if (this.pictureBox_Camera.Image != null && (int)this.numericUpDown1.Value > 0 && (int)this.numericUpDown2.Value > 0)
                {
                    Bitmap resultImage = new Bitmap((int)this.numericUpDown1.Value, (int)this.numericUpDown2.Value);
                    Graphics g = Graphics.FromImage(resultImage);
                    g.CopyFromScreen(new Point(this.mf.Location.X + 1, this.mf.Location.Y + 1), new Point(6, 6 + (isWin7 ? 2 : 0)), new Size(resultImage.Size.Width, resultImage.Size.Height - (6 + (isWin7 ? 2 : 0))));
                    if (!string.IsNullOrEmpty(XH))
                    {
                        string str = "";
                        if (this.XH != "")
                        {
                            str = this.XH;
                        }
                        else if (this.SFZH != "")
                        {
                            str = this.SFZH;
                        }
                        else if (this.KSH != "")
                        {
                            str = this.KSH;
                        }
                        if (this.checkBox2.Checked)
                        {
                            str = XM + " " + str;
                        }
                        int txtWidth = (int)(g.MeasureString(str, new Font("宋體", 9)).Width * 1.1);
                        Rectangle rec = new Rectangle((resultImage.Width - txtWidth) / 2, resultImage.Height - 16, txtWidth, 15);
                        g.FillRectangle(Brushes.White, rec);
                        StringFormat sf = new StringFormat();
                        sf.LineAlignment = StringAlignment.Center;
                        sf.Alignment = StringAlignment.Center;
                        rec.Height++;
                        g.DrawString(str, new Font("宋體", 9), Brushes.Black, rec, sf);
                    }
                    this.pictureBox_tx.Image = resultImage;
                }
                else
                {
                    this.pictureBox_tx.Image = null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
//選擇攝像裝置
private void cmbCaptureDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbCaptureDevice.SelectedItem != null)
            {
                this.cmbDeviceCapability.Items.Clear();
                VideoCaptureDevice device = new VideoCaptureDevice(((DeviceInfo)this.cmbCaptureDevice.SelectedItem).MonikerString);
                for (int i = 0; i < device.VideoCapabilities.Length; i++)
                {
                    VideoCapabilities capabilities = device.VideoCapabilities[i];
                    DeviceCapabilityInfo item = new DeviceCapabilityInfo(capabilities.FrameSize);
                    this.cmbDeviceCapability.Items.Add(item);
                }
                DeviceInfo selectedItem = (DeviceInfo)this.cmbCaptureDevice.SelectedItem;
                if (this.captureAForge != null)
                {
                    this.captureAForge.NewFrame -= new NewFrameEventHandler(this.captureAForge_NewFrame);
                    //this.captureAForge.SnapshotFrame -= new NewFrameEventHandler(this.captureAForge_SnapshotFrame);
                    if (this.captureAForge.IsRunning)
                    {
                        this.captureAForge.SignalToStop();
                    }
                    this.captureAForge.WaitForStop();
                    this.captureAForge = null;
                }
                this.captureAForge = new VideoCaptureDevice(selectedItem.MonikerString);
                this.captureAForge.ProvideSnapshots = true;
                this.captureAForge.NewFrame += new NewFrameEventHandler(this.captureAForge_NewFrame);
                //this.captureAForge.SnapshotFrame += new NewFrameEventHandler(this.captureAForge_SnapshotFrame);
                if (this.cmbDeviceCapability.Items.Count > 0)
                {
                    this.cmbDeviceCapability.SelectedIndex = 0;
                }
            }
        }
//選擇解析度
 private void cmbDeviceCapability_SelectedIndexChanged(object sender, EventArgs e)
        {
            string[] strArray = this.cmbDeviceCapability.Text.Trim().Split(new char[] { 'x' });
            int width = int.Parse(strArray[0]);
            int height = int.Parse(strArray[1]);
            if (this.captureAForge != null)
            {
                if (this.captureAForge.IsRunning)
                {
                    this.captureAForge.SignalToStop();
                }
                this.captureAForge.WaitForStop();
                this.captureAForge.DesiredFrameSize = new Size(width, height);
                this.captureAForge.DesiredSnapshotSize = new Size(width, height);

                //this.captureAForge.DesiredFrameRate = 1000;

                this.captureAForge.Start();

            }
        }
//設置數據源大小     
private void comboBox_SizeMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.comboBox_SizeMode.Text)
            {
                case "預設(原始大小)":
                    this.pictureBox_Camera.SizeMode = PictureBoxSizeMode.Normal;
                    break;
                case "居中(原始大小)":
                    this.pictureBox_Camera.SizeMode = PictureBoxSizeMode.CenterImage;
                    break;
                case "填充(拉伸圖像)":
                    this.pictureBox_Camera.SizeMode = PictureBoxSizeMode.StretchImage;
                    break;
                case "填充(保持比例)":
                    this.pictureBox_Camera.SizeMode = PictureBoxSizeMode.Zoom;
                    break;
            }
        }
//保存照片
private void buttonSave_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = Path.Combine(Application.StartupPath, "StuImages", "Newstuimages", this.XH + ".JPG");
                if (!this.checkBox1.Checked && File.Exists(filename))
                {
                    if (MessageBox.Show("該生已經有照片文件,是否覆蓋?     ", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    {
                        //存儲到本地
                        this.pictureBox_tx.Image.Save(filename);
                        //OnDataChanged(this, new DataEventArgs(string.Format("頭像採集(覆蓋),學號:{0},姓名:{1},考生號:{2},身份證號:{3}", this.XH, this.XM, this.KSH, this.SFZH)));
                        this.txtKSH.Focus();
                        this.txtKSH.SelectAll();
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    this.pictureBox_tx.Image.Save(filename);
                    //OnDataChanged(this, new DataEventArgs(string.Format("頭像採集,學號:{0},姓名:{1},考生號:{2},身份證號:{3}", this.XH, this.XM, this.KSH, this.SFZH)));
                    this.txtKSH.Focus();
                    this.txtKSH.SelectAll();
                }
                this.timer1.Start();
            }
            catch
            {

            }
            finally
            {
                //啟用下麵一行,點擊保存後頭像會立即啟動刷新
                //this.timer1.Start();
                this.btnSave.Enabled = false;
            }
        }

保存照片可以選擇自動覆蓋同名照片或者在照片中加入水印效果。

操作時候可以自行拖動長方形的框進行選擇拍照

 源碼下載:http://files.cnblogs.com/files/luoxiaozhao/Image_acquisitionForm.rar

請支持原創,轉載請標明來源。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 安裝vim 命令 一般模式 shift 4 行尾 shift 6 或 0行首 gg 頂部 G 下部 複製 yy 剪切幾行 數字 dd p粘貼 /和? 查找 1,100s/iptable/ip/g 第一行到100行 把iptable替換成ip g全局 1,$s/iptable/ip/g 全部選擇 %s ...
  • Git是目前世界上最先進的分散式版本控制系統(沒有之一)。使用Svn的請參考《版本控制-svn伺服器搭建和常用命令(centos 6.3)》,下麵介紹Git的常用命令 常用命令 簡單版 升級版 其他 伺服器搭建 本地伺服器搭建 Gitolite搭建 一、簡單版 1、創建版本庫 2、新增修改,新增文件 ...
  • 寫在前面的話 1.LAMP環境搭建請查看這篇日誌:http://www.cnblogs.com/yichong/p/6038686.html 2.這隻是一篇簡單的Discuz安裝教程,深入內容以後會講到。 3.Discu-3.2下載路徑:http://download.comsenz.com/Dis ...
  • 一個技術汪的開源夢 —— 目錄 想必大家在項目開發的時候應該都在程式中調用過自己內部的介面或者使用過第三方提供的介面,咱今天不討論 REST ,最常用的請求應該就是 GET 和 POST 了,那下麵開始講解對於 Http 請求客戶端的簡單封裝。 首先,說一個好消息 就是 .Net Core 已將之前 ...
  • 文件與文件夾操作主要用到以下幾個類: 1.File類:提供用於創建、複製、刪除、移動和打開文件的靜態方法,並協助創建 FileStream 對象。 msdn:http://msdn.microsoft.com/zh-cn/library/system.io.file(v=VS.80).aspx 2.... ...
  • 最近需要將一張圖片上傳並按指定位置剪裁,後來在網上找了一個剪裁圖片的插件,但是只有前臺沒有後端,然後我各種百度,並最終完成,特此寫一篇博客略表紀念。 前臺我就不說了,用的cropper插件,有興趣的自己去百度找找吧。jQuery之家 有這個插件。 下麵是代碼: 上面代碼中用到我自己創建了一個ImgS ...
  • 一、說明 AspNetPager.dll這個分頁控制項主要用於asp.net webform網站,現將整理代碼如下 二、代碼 1、首先在測試頁面Default.aspx頁面添加引用 2、寫一個Repeater列表控制項用於顯示數據 3、添加 PageSize屬性是用於設置每頁顯示的數量 4、後臺代碼綁定 ...
  • ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...