C#で画像ファイルをリサイズ(拡大・縮小)するCLIコマンド

C# コンピュータ
C#

コマンドラインから画像ファイルをリサイズ(拡大・縮小)します。

プロジェクトの作成

mkdir ResizeImage
cd ReizeImage
dotnet new console
dotnet add package System.CommandLine --prerelease
dotnet add package OpenCvSharp4
dotnet add package OpenCvSharp4.Windows
dotnet add package OpenCvSharp4.Extensions

ソースコード

using System.CommandLine;
using OpenCvSharp;

namespace ResizeImage;
class Program
{
    static readonly string AppName = "Resize";
    static void Filter(FileInfo file, double scale, InterpolationFlags interpolationFlags, string dir)
    {
        if (!File.Exists(file.FullName)) return;
        if (dir == "")
        {
            dir = Path.Join(file.DirectoryName ?? ".", AppName);
        }
        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }
        var src = Cv2.ImRead(file.FullName);
        var dst = new Mat();
        Cv2.Resize(src, dst, new OpenCvSharp.Size(0,0), scale, scale, interpolationFlags);
        string outFile = Path.Join(dir, file.Name);
        Cv2.ImWrite(outFile, dst);
        Console.WriteLine($"{outFile}");
    }
    static async Task<int> Main(string[] args)
    {
        var fileOption = new Option<FileInfo?>(
            name: "--file",
            description: "入力画像ファイル"
        ){ IsRequired = true };
        var scaleOption = new Option<double>(
            name: "--scale",
            description: "倍率",
            getDefaultValue: () => 0.5d
        ){ IsRequired = true };
        var interpolationFlagsOptions = new Option<InterpolationFlags>(
            name: "--InterpolationFlags",
            description: "補完方法",
            getDefaultValue: () => InterpolationFlags.Area
        );
        var dirOption = new Option<string>(
            name: "--dir",
            description: "出力先のディレクトリ",
            getDefaultValue: () => ""
        ){ IsRequired = true };
        var rootCommand = new RootCommand(
            "画像ファイルをリサイズ"
        );
        rootCommand.AddOption(fileOption);
        rootCommand.AddOption(scaleOption);
        rootCommand.AddOption(interpolationFlagsOptions);
        rootCommand.AddOption(dirOption);

        rootCommand.SetHandler((file, scale, interpolationFlags, dir) => 
            {
                Filter(file!, scale, interpolationFlags, dir);
            },
            fileOption, scaleOption, interpolationFlagsOptions, dirOption);

        return await rootCommand.InvokeAsync(args);
    }
}
Download

コメント