.NET에서 이미지 처리 작업을 할 때 일반적인 필요성은 여러 이미지를 결합하는 것입니다 - 종종 다른 크기 - 하나의 출력으로.일반적인 사용 사례에는 콜라지, 스프리트 잎, 접촉 폴더 또는 마케팅 밴드가 포함됩니다.이 튜토리얼은 Aspose.Imaging for .Net를 사용하여 이미지 조합 방법을 보여줍니다 레이아웃에 대한 정확한 제어 : 좌석 (수평 / 수평), 일치 (위 / 중앙 / 하단 및 왼쪽 / 중심 / 오른쪽), 외부 패딩 및 이미지 사이의 공간. Graphics
화재
무엇을 만들 것인가
- 배열 : * 수평 또는 수직
- 링크 : *
수평 레이아웃 → 수직 조정:
Top
,Middle
,Bottom
수직 레이아웃 → 수평 조정:
Left
,Center
,Right
Padding: 외부 패딩 및 항목 간 공간
- 배경 : * 단단한 색상 채우기
포맷: 로드 혼합 형식 (JPG, PNG, 등)을 제외하고 Png/JPEG
완전한 예제
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.Imaging;
using Aspose.Imaging.ImageOptions;
namespace ImagingMergeDemo
{
public enum MergeAxis { Horizontal, Vertical }
public enum VAlign { Top, Middle, Bottom }
public enum HAlign { Left, Center, Right }
public static class ImageMerger
{
/// <summary>
/// Merges input images into a single image with alignment and padding.
/// </summary>
/// <param name="inputPaths">List of source image file paths.</param>
/// <param name="axis">Horizontal or Vertical stacking.</param>
/// <param name="outerPadding">Padding around the whole collage (in pixels).</param>
/// <param name="spacing">Spacing between images (in pixels).</param>
/// <param name="bgColor">Background color for the canvas.</param>
/// <param name="verticalAlign">Only used when axis == Horizontal (Top/Middle/Bottom inside the row).</param>
/// <param name="horizontalAlign">Only used when axis == Vertical (Left/Center/Right inside the column).</param>
/// <param name="outputPath">Destination file path. Extension determines encoder (e.g., .png, .jpg).</param>
public static void Merge(
IReadOnlyList<string> inputPaths,
MergeAxis axis,
int outerPadding,
int spacing,
Color bgColor,
VAlign verticalAlign,
HAlign horizontalAlign,
string outputPath)
{
if (inputPaths is null || inputPaths.Count == 0)
throw new ArgumentException("No input images provided.");
// Load all images first so we can compute canvas size.
var loaded = new List<Image>(inputPaths.Count);
try
{
foreach (var p in inputPaths)
{
var img = Image.Load(p);
loaded.Add(img);
}
// Compute canvas size.
// For horizontal axis: width = sum(widths) + spacings + 2*outerPadding
// height = max(heights) + 2*outerPadding
// For vertical axis: height = sum(heights) + spacings + 2*outerPadding
// width = max(widths) + 2*outerPadding
int totalWidth, totalHeight;
if (axis == MergeAxis.Horizontal)
{
int sumWidths = 0, maxH = 0;
for (int i = 0; i < loaded.Count; i++)
{
sumWidths += loaded[i].Width;
maxH = Math.Max(maxH, loaded[i].Height);
}
totalWidth = sumWidths + ((loaded.Count - 1) * spacing) + 2 * outerPadding;
totalHeight = maxH + 2 * outerPadding;
}
else
{
int sumHeights = 0, maxW = 0;
for (int i = 0; i < loaded.Count; i++)
{
sumHeights += loaded[i].Height;
maxW = Math.Max(maxW, loaded[i].Width);
}
totalHeight = sumHeights + ((loaded.Count - 1) * spacing) + 2 * outerPadding;
totalWidth = maxW + 2 * outerPadding;
}
// Create canvas (use PNG by default for lossless output; you can switch to JPEGOptions)
using var canvas = Image.Create(new PngOptions(), totalWidth, totalHeight);
// Draw on canvas
using var g = new Graphics(canvas);
g.Clear(bgColor);
int cursorX = outerPadding;
int cursorY = outerPadding;
for (int i = 0; i < loaded.Count; i++)
{
var img = loaded[i];
int drawX, drawY;
if (axis == MergeAxis.Horizontal)
{
// X flows left -> right
drawX = cursorX;
// Y depends on vertical alignment vs tallest height
drawY = verticalAlign switch
{
VAlign.Top => outerPadding,
VAlign.Middle => outerPadding + (totalHeight - 2 * outerPadding - img.Height) / 2,
VAlign.Bottom => outerPadding + (totalHeight - 2 * outerPadding - img.Height),
_ => outerPadding
};
// Draw and move X cursor
g.DrawImage(img, new Rectangle(drawX, drawY, img.Width, img.Height));
cursorX += img.Width + spacing;
}
else
{
// Y flows top -> bottom
drawY = cursorY;
// X depends on horizontal alignment vs widest width
drawX = horizontalAlign switch
{
HAlign.Left => outerPadding,
HAlign.Center => outerPadding + (totalWidth - 2 * outerPadding - img.Width) / 2,
HAlign.Right => outerPadding + (totalWidth - 2 * outerPadding - img.Width),
_ => outerPadding
};
// Draw and move Y cursor
g.DrawImage(img, new Rectangle(drawX, drawY, img.Width, img.Height));
cursorY += img.Height + spacing;
}
}
// Save with encoder that matches extension
SaveByExtension(canvas, outputPath);
}
finally
{
// Dispose loaded images
foreach (var img in loaded)
img.Dispose();
}
}
private static void SaveByExtension(Image image, string outputPath)
{
var ext = Path.GetExtension(outputPath).ToLowerInvariant();
ImageOptionsBase opts = ext switch
{
".jpg" or ".jpeg" => new JpegOptions { Quality = 90 },
".png" => new PngOptions(),
_ => new PngOptions() // default to PNG
};
image.Save(outputPath, opts);
}
}
// Example usage
public class Program
{
public static void Main()
{
var inputs = new List<string>
{
"image1.jpg",
"image2.png",
"image3.jpg"
};
// Horizontal strip, vertically centered, with padding/spacing
ImageMerger.Merge(
inputPaths: inputs,
axis: MergeAxis.Horizontal,
outerPadding: 20,
spacing: 10,
bgColor: Color.White,
verticalAlign: VAlign.Middle,
horizontalAlign: HAlign.Center, // ignored for horizontal axis
outputPath: "merged_horizontal.png"
);
// Vertical stack, horizontally right-aligned
ImageMerger.Merge(
inputPaths: inputs,
axis: MergeAxis.Vertical,
outerPadding: 20,
spacing: 12,
bgColor: Color.FromArgb(255, 245, 245, 245),
verticalAlign: VAlign.Middle, // ignored for vertical axis
horizontalAlign: HAlign.Right,
outputPath: "merged_vertical.jpg"
);
}
}
}
단계별 가이드
단계 1 : 사진을 업로드
모든 입력 이미지로 업로드 Image.Load(path)
그들은 그림을 그리기 전까지 살아있게 유지하고, 그 다음에 배제하십시오.
단계 2 : 출력 크기를 결정합니다.
- 수평 배열 : 폭 = 폭의 합 + 공간 + 외부 패딩; 고도 = 최대 높이 + 야외 패팅.
- ** 수직 배열**: 높이 = 높이가 + 공간 + 외부 굴착; 폭 = 최대 폭 + 밖 굽착.
3단계: 출력 캔버스를 만드는 방법
사용하여 만들기 Image.Create(new PngOptions(), width, height)
(또는 JpegOptions
당신이 손실 출력을 선호하는 경우). 배경 색상으로 밝은.
단계 4 : 조정 및 패딩 설정
- 수평 합병 → 계산 Y by
Top / Middle / Bottom
. - 수직 합병 → 계산 X by
Left / Center / Right
. - Apply
outerPadding
그리고spacing
일관되게
5단계 : 각각의 그림을 그리십시오.
사용하기 Graphics.DrawImage(image, new Rectangle(x, y, image.Width, image.Height))
.
단계 6 : 결과를 저장
출력 파일 이름 확장을 기반으로 코더를 선택하십시오 (예 : .png
→ PngOptions
, .jpg
→ JpegOptions { Quality = … }
).
모범 사례
- 정상화 형식: 투명한 배경을 필요로 하는 경우 PNG로 저장합니다.
Quality
. - Guardrails: 입력 목록을 검증하고, 실종된 파일을 처리하며, OOM을 피하기 위해 최대 캔버스 크기를 고려합니다.
- 이용 가능* :
Image
,Graphics
이용 가능 - 사용 가능using
또는try/finally
.
- 이용 가능* :
- 색상 일관성: 입력이 혼합 색상 유형을 가지고 있다면, Aspose 결함에 의존하거나 필요할 때 명시적으로 변환하십시오.
- Batching: 큰 세트의 경우, 이동하는 동안 스트림 출력 또는 여러 타일 / 페이지를 만듭니다.