Chuyển hình hình ảnh bằng một góc tự nguyện với một nền minh bạch là một yêu cầu thường xuyên cho các galeries, bảng điều khiển, và công cụ thiết kế trong .NET. Aspose.Imaging for .Net cung cấp một API trực tiếp để tải lên một bức ảnh, xoay nó bằng góc tùy chỉnh và lưu vào một định dạng hỗ trợ tính toàn diện.
Một ví dụ đầy đủ
// 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}");
}
}
}
}
}
- Làm thế nào nó hoạt động *
Image.Load
mở nguồn. code checks and casts toRasterImage
cho các hoạt động raster.raster.Rotate(angle, expandCanvas, Color.Transparent)
xoay bằng bất kỳ mức giá trị nào.- Tiết kiệm với
PngOptions
duy trì sự minh bạch - Mode Batch đi qua một cây thư mục, xoay các định dạng được hỗ trợ, và viết PNG.
Hướng dẫn từng bước
1) Tải hình ảnh
Sử dụng Image.Load
để mở file nguồn. Cast to RasterImage
Nếu bạn cần các thành viên đặc biệt.
using (var image = (RasterImage)Image.Load(inputPath))
{
// work with the image here
}
2) Trượt theo bất kỳ góc
Lời gọi Rotate(angle, expandCanvas, backgroundColor)
.
angle
ở cấp độexpandCanvas = true
tránh nhấp nháy bằng cách khôi phục lưỡi để phù hợp với các giới hạn xoayColor.Transparent
giữ nền minh bạch nếu định dạng output hỗ trợ alpha
image.Rotate(17, true, Color.Transparent);
3) Lưu vào một định dạng hỗ trợ minh bạch
PNG hỗ trợ minh bạch. sử dụng PngOptions
để tiết kiệm kết quả xoay với kênh alpha được bảo tồn.
image.Save(outputPath, new PngOptions());
Các tùy chọn thực tế
- Tránh cài đặt *: Set
expandCanvas = true
Khi xoay bằng các góc không phải
- Tránh cài đặt *: Set
- Các nền khác nhau: vượt qua một vững chắc
Color
Thay vìColor.Transparent
Nếu bạn muốn một nền đầy đủ - *Không thua lỗ: Tốt nhất PNG cho UI, logos và overlays đòi hỏi ranh giới và minh bạch
- Photo: nếu bạn không cần minh bạch, tiết kiệm như JPEG có thể làm giảm kích thước tệp
Các pitfalls và fixes chung
- Hình nền minh bạch mất*tiết kiệm với
PngOptions
hoặc định dạng khác hỗ trợ alpha. JPEG không cung cấp sự minh bạch.
- Hình nền minh bạch mất*tiết kiệm với
**Một phần của hình ảnh bị mất sau khi xoay*Sử dụng
expandCanvas = true
để phát triển các canvas để nội dung xoay phù hợp.Điều kiện sau khi xoayNếu nguồn của bạn có độ phân giải thấp, hãy cân nhắc lặp lại đầu vào với độ sáng cao hơn trước khi quay, sau đó giảm quy mô sau khi tiết kiệm để giảm các tác phẩm có thể nhìn thấy.
- Bộ nhớ và hình ảnh lớn*Cài đặt hình ảnh một cách nhanh chóng và tránh tải nhiều tệp lớn cùng một lúc. Thiết lập ổ đĩa caching cho các gói lớn nếu cần thiết.
Mini danh sách kiểm tra
- tải với
Image.Load
- xoay với
image.Rotate(angle, true, Color.Transparent)
- tiết kiệm với
new PngOptions()
Đối với minh bạch - Sử dụng nền vững chắc nếu minh bạch không được yêu cầu
- Chứng nhận kết quả trực quan cho các tài sản chính
FAQ
Những định dạng nào giữ minh bạch sau khi quayPNG và các định dạng có khả năng alpha khác. JPEG không giữ minh bạch.
Làm thế nào để xoay mà không mở rộng canvas*Pass
expandCanvas = false
Nội dung bên ngoài các giới hạn ban đầu sẽ được clip.Tôi có thể xoay bằng bất kỳ góc nào*Có. Parameter góc chấp nhận bất kỳ giá trị bằng số nào.