투명한 배경을 가진 자발적인 각도에서 이미지를 회전하는 것은 .NET의 갤러리, 다스보드 및 디자인 도구에 대한 빈번한 요구 사항입니다. Aspose.Imaging for .Net는 이미지를 로드하고, 사용자 지정 각도로 회전에 맞추고, 투표성을 지원하는 형식으로 저장하는 직접 API를 제공합니다.
완전한 예제
// File: Program.cs
// Requires NuGet: Aspose.Imaging
using System;
using System.Collections.Generic;
using System.IO;
using Aspose.Imaging;
using Aspose.Imaging.ImageOptions;
namespace RotateTransparentDemo
{
public static class Program
{
public static int Main(string[] args)
{
try
{
if (args.Length == 0)
{
// Single-file demo paths. Replace with your own files or pass CLI args.
var input = "input.png"; // source can be PNG, JPG, etc.
var output = "rotated-output.png"; // must be PNG to preserve transparency
RotateSingle(input, output, angleDegrees: 17f, expandCanvas: true);
Console.WriteLine($"Saved: {output}");
return 0;
}
// CLI:
// 1) Single file:
// RotateTransparentDemo.exe <inputPath> <outputPath> <angleDegrees> [expandCanvas:true|false]
//
// 2) Batch folder:
// RotateTransparentDemo.exe --batch <inputDir> <outputDir> <angleDegrees> [expandCanvas:true|false]
if (args[0].Equals("--batch", StringComparison.OrdinalIgnoreCase))
{
if (args.Length < 4)
{
Console.Error.WriteLine("Usage: --batch <inputDir> <outputDir> <angleDegrees> [expandCanvas:true|false]");
return 2;
}
var inputDir = args[1];
var outputDir = args[2];
var angle = float.Parse(args[3]);
var expandCanvas = args.Length >= 5 ? bool.Parse(args[4]) : true;
BatchRotate(inputDir, outputDir, angle, expandCanvas);
Console.WriteLine($"Batch complete. Output in: {outputDir}");
return 0;
}
else
{
if (args.Length < 3)
{
Console.Error.WriteLine("Usage: <inputPath> <outputPath> <angleDegrees> [expandCanvas:true|false]");
return 2;
}
var inputPath = args[0];
var outputPath = args[1];
var angle = float.Parse(args[2]);
var expandCanvas = args.Length >= 4 ? bool.Parse(args[3]) : true;
RotateSingle(inputPath, outputPath, angle, expandCanvas);
Console.WriteLine($"Saved: {outputPath}");
return 0;
}
}
catch (Exception ex)
{
Console.Error.WriteLine("Error: " + ex.Message);
return 1;
}
}
/// <summary>
/// Rotates a single image by an arbitrary angle and preserves transparency in the output PNG.
/// </summary>
private static void RotateSingle(string inputPath, string outputPath, float angleDegrees, bool expandCanvas)
{
if (!File.Exists(inputPath))
throw new FileNotFoundException("Input image not found.", inputPath);
// If you expect large images or batches, you can enable disk cache to reduce RAM pressure:
// Aspose.Imaging.Cache.CacheType = Aspose.Imaging.Cache.CacheType.CacheOnDisk;
// Aspose.Imaging.Cache.CacheFolder = Path.GetFullPath(".imaging-cache");
// Aspose.Imaging.Cache.CacheSize = 512L * 1024 * 1024; // 512 MB
using (var image = Image.Load(inputPath))
{
// Raster operations are available on RasterImage
if (image is not RasterImage raster)
throw new InvalidOperationException("Loaded image is not a raster image.");
// Rotate by an arbitrary angle. Set expandCanvas to true to avoid clipping.
// Color.Transparent keeps the background transparent for alpha-capable formats.
raster.Rotate(angleDegrees, expandCanvas, Color.Transparent);
// Save as PNG to preserve alpha channel
var pngOptions = new PngOptions
{
// Most cases do not need explicit color type; leaving defaults preserves alpha.
// Uncomment if you want to force RGBA:
// ColorType = Aspose.Imaging.FileFormats.Png.PngColorType.TruecolorWithAlpha
};
// Ensure output directory exists
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outputPath)) ?? ".");
raster.Save(outputPath, pngOptions);
}
}
/// <summary>
/// Rotates all supported images in a folder and writes PNG outputs with transparency preserved.
/// </summary>
private static void BatchRotate(string inputDir, string outputDir, float angleDegrees, bool expandCanvas)
{
if (!Directory.Exists(inputDir))
throw new DirectoryNotFoundException("Input directory not found: " + inputDir);
Directory.CreateDirectory(outputDir);
// Common raster extensions. Adjust as needed.
var extensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff", ".webp"
};
var files = Directory.GetFiles(inputDir, "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
var ext = Path.GetExtension(file);
if (!extensions.Contains(ext))
continue;
var rel = Path.GetRelativePath(inputDir, file);
var relBase = Path.ChangeExtension(rel, ".png"); // output is PNG to keep transparency
var outPath = Path.Combine(outputDir, relBase);
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(outPath)) ?? ".");
try
{
RotateSingle(file, outPath, angleDegrees, expandCanvas);
Console.WriteLine($"OK {rel} -> {relBase}");
}
catch (Exception ex)
{
Console.WriteLine($"ERR {rel}: {ex.Message}");
}
}
}
}
}
- 어떻게 작동하는지 *
Image.Load출처를 엽니 다. 코드는 확인하고 삽입합니다.RasterImage라스터 작업을 위한raster.Rotate(angle, expandCanvas, Color.Transparent)모든 정도의 가치로 회전합니다.- 저축과 함께
PngOptions투명성을 유지한다. - 배치 모드는 디렉토리 나무를 걷고, 지원되는 형식을 회전하고, PNG를 작성합니다.
단계별 가이드
1) 이미지를 업로드
사용하기 Image.Load 원본 파일을 엽니 다.Cast to RasterImage 특정 멤버가 필요하다면
using (var image = (RasterImage)Image.Load(inputPath))
{
// work with the image here
}
2) 각각의 각도에서 회전
전화 Rotate(angle, expandCanvas, backgroundColor).
angle등급에 있는expandCanvas = true회전 한 경계에 맞게 캔버스를 재구성함으로써 클립을 피하십시오.Color.Transparent출력 형식이 alpha를 지원하는 경우 배경을 투명하게 유지합니다.
image.Rotate(17, true, Color.Transparent);
3) 투명성을 지원하는 형식으로 저장
PNG는 투명성을 지원합니다. PngOptions 보존된 알파 채널과 함께 회전 출력을 저장합니다.
image.Save(outputPath, new PngOptions());
실용적인 옵션
- ** 클립을 피하십시오** : 세트
expandCanvas = true오른쪽 모서리로 회전할 때 - 오파크 배경 : 단단한 통과
Color대신에Color.Transparent만약 가득한 배경을 원한다면 - ** 손실없는 출력**: 크리스프 경계와 투명성을 필요로하는 UI, 로고 및 위장에 대한 PNG를 선호합니다.
- 사진: 투명성이 필요하지 않으면 JPEG로 저장하면 파일 크기를 줄일 수 있습니다.
일반적인 피트폴리와 고정
- 잃어버린 투명한 배경*저장함으로써
PngOptions또는 알파를 지원하는 다른 형식. JPEG는 투명성을 지원하지 않습니다.
- 잃어버린 투명한 배경*저장함으로써
그림의 일부는 회전 후 사라집니다사용하기
expandCanvas = true캔버스를 성장하여 회전된 콘텐츠가 적합합니다.** 회전 후 흔들리는 경계선**회전은 도서관 결함을 사용합니다.당신의 소스가 낮은 해상도 인 경우, 회복하기 전에 더 높은해상도로 입력을 재시작하는 것을 고려하고, 그 후에 저장하여 눈에 띄는 유물을 줄일 수 있습니다.
- 메모리 및 큰 이미지*이미지를 신속하게 배치하고 여러 개의 큰 파일을 동시에 충전하지 마십시오.필요한 경우 대형 팩을 위한 디스크 캐싱을 설정합니다.
미니 체크리스트
- 로드와 함께
Image.Load - 로트와 함께
image.Rotate(angle, true, Color.Transparent) - 저장함으로써
new PngOptions()투명성을 위해 - 투명성이 필요하지 않은 경우 견고한 배경을 사용하십시오.
- 핵심 자산에 대한 수출을 시각적으로 검증
FAQ
** 어떤 형식이 회전 후 투명성을 유지할 수 있습니까**PNG 및 기타 알파 용량 형식. JPEG는 투명성을 유지하지 않습니다.
** 캔버스를 확장하지 않고 어떻게 회전할 수 있습니까**패스 expandCanvas = false원본 제한 이외의 콘텐츠는 클립됩니다.
- 어떠한 각도에서든 회전할 수 있음*예. 각도 매개 변수는 모든 숫자 등급 값을 수락합니다.