[C#][WinForm]如何合併圖片

[C#][WinForm]如何合併圖片

看到網友發問,自己隨手記錄一下。

一般合併圖片大多情況有三種,水平、垂直、浮水印,這裡簡單實做一下。

 

來源兩張圖片

image image

水平合併

 private Image HorizontalMergeImages(Image img1, Image img2)
        {
            Image MergedImage = default(Image);
            Int32 Wide = 0;
            Int32 High = 0;          
            Wide = img1.Width + img2.Width;//設定寬度           
            if (img1.Height >= img2.Height)
            {
                High = img1.Height;
            }
            else
            {
                High = img2.Height;
            }  
            Bitmap mybmp = new Bitmap(Wide, High);
            Graphics gr = Graphics.FromImage(mybmp); 
            //處理第一張圖片
            gr.DrawImage(img1, 0, 0);           
            //處理第二張圖片
            gr.DrawImage(img2, img1.Width, 0);
            MergedImage = mybmp;
            gr.Dispose();           
            return MergedImage;
        }    

結果

image

 

垂直合併

 private Image HorizontalMergeImages(Image img1, Image img2)
        {
            Image MergedImage = default(Image);
            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, High);
            Graphics gr = Graphics.FromImage(mybmp); 
            //處理第一張圖片
            gr.DrawImage(img1, 0, 0);           
            //處理第二張圖片
            gr.DrawImage(img2, 0, img1.Height);
            MergedImage = mybmp;
            gr.Dispose();           
            return MergedImage;
        }  

結果

image

 

圖片浮水印

private Image MarkImage(Image img1, Image img2)
        {          
            Image MergedImage = default(Image);
            //設定背景圖片
            Graphics gr = System.Drawing.Graphics.FromImage(img1); 
            //新建logo浮水印圖片
            Bitmap Logo = new Bitmap(img2.Width, img2.Height); 
            Graphics tgr = Graphics.FromImage(Logo);
            ColorMatrix cmatrix = new ColorMatrix();  
            //設定圖片色彩(透明度)
            cmatrix.Matrix33 = 0.5F;  
            ImageAttributes imgattributes = new ImageAttributes();
            imgattributes.SetColorMatrix(cmatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            tgr.DrawImage(img2, new Rectangle(0, 0, Logo.Width, Logo.Height), 0, 0, Logo.Width, Logo.Height, GraphicsUnit.Pixel, imgattributes);
            tgr.Dispose();
            //logo圖片位置
            gr.DrawImage(Logo, img1.Width/3,10);           
            gr.Dispose();
            MergedImage = img1;
            return MergedImage;
        }

結果

image