编程技术 · 2018 年 12 月 06 日 0

C#合并保存多个图片Image

原文链接 https://blog.csdn.net/CHEN504390172/article/details/22920663

        /// <summary>
        /// 打开图片列表,存放在列表里
        /// </summary>
        private void OpenImage()
        {
           fileDialog.RestoreDirectory = true;
            fileDialog.Multiselect = true;
            fileDialog.Filter = "JPG文件(*.jpg)|*.jpg|BMP文件(*.bmp)|*.bmp|TFT文件(*.tft)|*.tft|所有文件(*.*)|*.*";            
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                foreach (string s in fileDialog.FileNames)
                {                 
                    this.listView1.Items.Add(s);             
                }
            }
        }
        Image MergedImage = default(Image);
        string savePath;
        string saveImgPath;
 
        /// <summary>
        /// 合并保存图片
        /// </summary>
        /// <param name="img1"></param>
        /// <param name="img2"></param>
        private void HorizontalMergeImages(Image img1, Image img2)
        {            
           Int32 Wide = 0;
           Int32 High = 0;
         
           High = img1.Height + img2.Height;//設定高度           
 
           if (img1.Width >= img2.Width)
           {
               Wide = img1.Width;
           }
           else
           {
               Wide = img2.Width;
           }
           Bitmap mybmp = new Bitmap(Wide / 2, High / 2);         
           Graphics gr = Graphics.FromImage(mybmp);
           gr.DrawImage(img1, new Rectangle(0, 0, img1.Width / 2, img1.Height / 2));
           gr.DrawImage(img2, new Rectangle(0, img1.Height / 2, img2.Width / 2, img2.Height / 2));                   
          
           MergedImage = mybmp;
           saveImgPath = savePath + "\\" + DateTime.Now.ToString("yyyyMMHHmmffffff") + ".jpg";
           textBox1.Text = saveImgPath;
           MergedImage.Save(saveImgPath);
           
           gr.Dispose();
           mybmp.Dispose();                   
       }
        /// <summary>
        /// 从列表里保存图片
        /// </summary>
        public void MerAndSave()
        {
            if (savePath == null)
            {
                MessageBox.Show("请先设置图片的保存路径!");
                return;
            }
            stw.Start();
            this.ProgressSpeed.Value = 0;
            this.ProgressSpeed.Maximum = listView1.Items.Count;
            Image img1;
            Image img2 = pictureBox2.Image;
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                Application.DoEvents();
                img1 = Image.FromFile(listView1.Items[i].Text.ToString());
                HorizontalMergeImages(img1, img2);
                this.ProgressSpeed.Value = i + 1;
                img1.Dispose();
            }
            stw.Stop();
            labelTime.Text = "一共使用时间" + stw.Elapsed.Seconds.ToString() + "秒";
            MessageBox.Show("合成图片成功");
            this.ProgressSpeed.Value = 0;
        }