本主题涵盖如何在 C# 中合并 photos。它包含环境配置、分步过程和可运行的代码片段,用于在 C# 中开发 照片连接器。您可以应用此信息,以便在不同操作系统的任何 .NET 支持的环境中使用此功能。
在 C# 中合并照片的步骤
- 使用 NuGet 包管理器插件设置环境以使用 Aspose.Imaging for .NET
- 创建图像列表并获取结果图像的大小
- 将图像组合成新图像并创建输出源
- 使用 JpegOptions 类对象设置不同的属性
- 使用 JpegImage 类导出合并的图像
这些步骤总结了在 C# 中组合照片的整个过程。首先,创建要合并为一张照片的多个图像的列表。因此,创建一张新图片并将其渲染为输出图像,然后根据您的需要将其保存到磁盘或流中。
C# 中合并照片的代码
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using Aspose.Imaging; | |
using Aspose.Imaging.ImageOptions; | |
using Aspose.Imaging.Sources; | |
class Program | |
{ | |
static void Main(string[] args) // Merge images into one image in C# | |
{ | |
// Set PDF license | |
new Aspose.Imaging.License().SetLicense("License.lic"); | |
// Create a list of images | |
string[] imagePaths = { "picture1.jpg", "picture2.jpg", "picture3.jpg" }; | |
// Get resulting image's size | |
List<Aspose.Imaging.Size> imageSizes = new List<Aspose.Imaging.Size>(); | |
foreach (string imagePath in imagePaths) | |
{ | |
using (RasterImage image = (RasterImage)Aspose.Imaging.Image.Load(imagePath)) | |
{ | |
imageSizes.Add(image.Size); | |
} | |
} | |
int newWidth = imageSizes.Max(size => size.Width); | |
int newHeight = imageSizes.Sum(size => size.Height); | |
// Combine images into new one | |
using (MemoryStream memoryStream = new MemoryStream()) | |
{ | |
// Create output source | |
StreamSource outputStreamSource = new StreamSource(memoryStream); | |
// Create jpeg options | |
JpegOptions options = new JpegOptions() | |
{ Quality = 100, Source = outputStreamSource }; | |
// Create output image | |
using (Aspose.Imaging.FileFormats.Jpeg.JpegImage newImage = | |
(Aspose.Imaging.FileFormats.Jpeg.JpegImage)Aspose.Imaging.Image.Create(options, newWidth, newHeight)) | |
{ | |
int stitchedHeight = 0; | |
// Merge images | |
foreach (string imagePath in imagePaths) | |
{ | |
using (RasterImage image = (RasterImage)Aspose.Imaging.Image.Load(imagePath)) | |
{ | |
Aspose.Imaging.Rectangle bounds = new Aspose.Imaging.Rectangle(0, stitchedHeight, image.Width, image.Height); | |
newImage.SaveArgb32Pixels(bounds, image.LoadArgb32Pixels(image.Bounds)); | |
stitchedHeight += image.Height; | |
} | |
} | |
// Save the merged image | |
newImage.Save("merged-image.jpg"); | |
} | |
} | |
System.Console.WriteLine("Done"); | |
} | |
} |
此代码片段足以在 C#* 中开发*图像组合器。它与 JpegImage 类一起创建输出图像,同时计算源图片的图像尺寸。然后它继续创建一个矩形并使用 Save 方法保存合并的输出图像。此外,您可以根据您的要求使用 JpegOptions 类自定义输出图像的多个属性,例如压缩类型、质量、颜色类型、分辨率单位等。
在本文中,我们学习了在 C# 中执行图像合并的过程。如果您想旋转图像,请阅读 如何在C#中旋转图像 上的文章。