以透明背景的任意角度旋转图像是 .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 保持透明度。
  • Batch 模式运行一个目录树,旋转支持的格式,并编写 PNG。

步骤指南

(一)下载图像

使用 Image.Load 打开源文件. 点击 RasterImage 如果你需要特定的会员。

using (var image = (RasterImage)Image.Load(inputPath))
{
    // work with the image here
}

(二)按任何角度旋转

呼叫 Rotate(angle, expandCanvas, backgroundColor).

  • angle 在等级中
  • expandCanvas = true 避免粘贴,重新调整管道,以适应旋转的边界
  • Color.Transparent 保持背景透明,如果输出格式支持Alpha
image.Rotate(17, true, Color.Transparent);

(三)保存到支持透明度的格式

PNG 支持透明度 使用 PngOptions 保存旋转输出与保存的阿尔法频道。

image.Save(outputPath, new PngOptions());

实用选项

  • ** 避免剪辑**:设置 expandCanvas = true 以非右角旋转时
  • Opaque 背景:通过坚固的背景 Color 而不是 Color.Transparent 如果你想要一个完整的背景
  • ** 无损输出**:优先使用 UI、LOGOS 和需要克里斯普边缘和透明度的表格的 PNG
  • ** 照片**:如果您不需要透明度,储蓄,因为JPEG可以减少文件大小

常见的折叠和修复

    • 透明背景失去*保存与 PngOptions 或其他支持 alpha 的格式. JPEG 不支持透明度。
  • 图像部分在旋转后失踪使用 expandCanvas = true 要生长通道,以便旋转内容合适。

  • ** 旋转后追逐的边缘**旋转使用图书馆故障. 如果您的源是低分辨率,考虑重定向输入到更高的解像度之前旋轉,然后下滑后保存以减少可见的物品。

    • 記憶與大圖像*快速配置图像,并避免同时加载许多大文件。

小型检查列表

  • 加载与 Image.Load
  • 旋转与 image.Rotate(angle, true, Color.Transparent)
  • 保存与 new PngOptions() 为了透明度
  • 使用坚固的背景,如果不需要透明度
  • 视觉验证关键资产的输出

FAQ

在旋转后保持透明度的格式PNG 和其他 Alpha 可用的格式. JPEG 不保留透明度。

** 如何在没有扩展管道的情况下旋转*Pass expandCanvas = false原始界限之外的内容将被剪辑。

“我可以从任何角度旋转”是的,角度参数接受任何数字等级值。

More in this category