c# 多张图片合成一张图片

本文介绍如何使用C#编程语言将多张图片合并成一张图片,详细讲解了实现过程,并提供了相关代码示例。
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            CombinImage();
        }
      /// <summary>
      /// 方法一
      /// 多张图片的合并
      /// </summary>
        static private void CombinImage()
        {
            const string folder = @"F:\测试图片";
            Image img1 = Image.FromFile(Path.Combine(folder, "测试1.png"));
            Bitmap map1 = new Bitmap(img1);
           
### 实现 C# 图片合成功能 为了实现多张图片合并成一张的功能,在 C# 中可以利用 `System.Drawing` 命名空间下的类来处理图像操作。下面展示了一个完整的例子,该方法能够接收一系列的图片文件,并按照指定的方向(水平或垂直)将它们合并。 #### 定义枚举用于指示合并方向 首先定义一个枚举类型用来表示图片应该被怎样排列组合: ```csharp /// <summary> /// 枚举:规定了两种可能的拼接方式——横向或是纵向。 /// </summary> public enum ImageMergeOrientation { Horizontal, Vertical } ``` #### 编写函数完成图片合并逻辑 接下来编写具体的业务逻辑代码如下所示: ```csharp using System; using System.Collections.Generic; using System.Drawing; using System.IO; public class ImageCombiner { /// <summary> /// 将多个图片对象按给定模式合并为单个新图片。 /// </summary> /// <param name="imagePaths">待合并的源图片路径列表。</param> /// <param name="outputPath">目标输出位置以及文件名。</param> /// <param name="orientation">设定合并后的布局样式,默认横排。</param> public static void CombineImages(List<string> imagePaths, string outputPath, ImageMergeOrientation orientation = ImageMergeOrientation.Horizontal) { List<Image> images = new(); foreach (var imagePath in imagePaths) using (FileStream fs = File.OpenRead(imagePath)) images.Add(Image.FromStream(fs)); int totalWidth = 0; // 总宽度 int maxHeight = 0; // 最大高度 if (orientation == ImageMergeOrientation.Horizontal) { foreach (Image img in images) { totalWidth += img.Width; if (img.Height > maxHeight) maxHeight = img.Height; } } else { foreach (Image img in images) { if (img.Width > totalWidth) totalWidth = img.Width; maxHeight += img.Height; } } Bitmap combinedBitmap = new(totalWidth, maxHeight); Graphics g = Graphics.FromImage(combinedBitmap); Point location = new(0, 0); foreach (Image img in images) { g.DrawImage(img, location.X, location.Y); if (orientation == ImageMergeOrientation.Horizontal) location.X += img.Width; else location.Y += img.Height; img.Dispose(); // 及时释放资源 } try { combinedBitmap.Save(outputPath); } finally { g.Dispose(); combinedBitmap.Dispose(); foreach (Image img in images) img.Dispose(); } } } ``` 此段程序实现了从磁盘读取一组JPEG格式的照片作为输入参数,根据传入的方向参数决定是以水平还是竖直的方式堆叠这些照片,最后把合成的结果保存至指定的位置[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值