C# 合併多張圖片

 public enum ImageMergeOrientation
    {
        Horizontal,
        Vertical
    }

 

//根據參數進行橫向或縱向合併圖片

//如果爲橫向,圖片高度爲最高的那張;如果縱向則寬度爲最寬的那張

private void CombineImages(FileInfo[] files, string toPath, ImageMergeOrientation mergeType)
        {
            //change the location to store the final image.
            var finalImage = toPath;
            var imgs = files.Select(f => Image.FromFile(f.FullName));
 
            var finalWidth = mergeType == ImageMergeOrientation.Horizontal ?
                imgs.Sum(img => img.Width) :
                imgs.Max(img => img.Width);
 
            var finalHeight = mergeType == ImageMergeOrientation.Vertical ?
                imgs.Sum(img => img.Height) :
                imgs.Max(img => img.Height);
 
            var finalImg = new Bitmap(finalWidth, finalHeight);
            Graphics g = Graphics.FromImage(finalImg);
            g.Clear(SystemColors.AppWorkspace);
 
            var width = finalWidth;
            var height = finalHeight;
            var nIndex = 0;
            foreach (FileInfo file in files)
            {
                Image img = Image.FromFile(file.FullName);
                if (nIndex == 0)
                {
                    g.DrawImage(img, new Point(0, 0));
                    nIndex++;
                    width = img.Width;
                    height = img.Height;
                }
                else
                {
                    switch (mergeType)
                    {
                        case ImageMergeOrientation.Horizontal:
                            g.DrawImage(img, new Point(width, 0));
                            width += img.Width;
                            break;
                        case ImageMergeOrientation.Vertical:
                            g.DrawImage(img, new Point(0, height));
                            height += img.Height;
                            break;
                        default:
                            throw new ArgumentOutOfRangeException("mergeType");
                    }
                }
                img.Dispose();
            }
            g.Dispose();
            finalImg.Save(finalImage, System.Drawing.Imaging.ImageFormat.Tiff);
            finalImg.Dispose();
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章