C#で作る画像を幅と高さを256の倍数に余白で調整するコンソールアプリ

コンピュータ

幅と高さを256で割り切れる数値になるように、白色の余白を加えることで調整します。

ソースコード

ファイル名:pad256.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
    <PackageReference Include="OpenCvSharp4.runtime.win" Version="4.11.0.20250507" />
  </ItemGroup>

</Project>

ファイル名:Opt.cs


public class Opt
{
    public string Input { get; set; } = "";
    public string? Output { get; set; } = null;
    public static Opt ParseArgs(string[] a)
    {
        var o = new Opt();
        string? key = null;
        foreach (var token in a)
        {
            if (token.StartsWith("-"))
            {
                key = token;
            }
            else
            {
                switch (key)
                {
                    case "-i": case "--in": o.Input = token; break;
                    case "-o": case "--out": o.Output = token; break;
                    default:
                        // 位置引数互換
                        if (string.IsNullOrEmpty(o.Input)) o.Input = token;
                        else if (o.Output is null) o.Output = token;
                        break;
                }
                key = null;
            }
        }
        return o;
    }
    public static void PrintHelp()
    {
        Console.Error.WriteLine(
@"Usage:
  pad256 -i <input> [options]
  pad256 <input> [output.png]

Options:
  -i, --in <path>          入力ファイル
  -o, --out <path>         出力ファイル(省略時: <input>_256.png)
");
    }

}

ファイル名:Program.cs



// C#で作る画像を幅と高さを256の倍数に余白で調整するコンソールアプリ

// ビルドコマンド
// dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true /p:IncludeAllContentForSelfExtract=true /p:SelfContained=true --output "exeの出力先のディレクトリ"
using OpenCvSharp;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length == 0 || args.Contains("-h") || args.Contains("--help"))
        {
            Opt.PrintHelp();
            Environment.Exit(1);
        }

        var opt = Opt.ParseArgs(args);
        if (string.IsNullOrWhiteSpace(opt.Input))
        {
            Opt.PrintHelp();
            Environment.Exit(1);
        }

        string output = opt.Output ?? Path.Combine(
            Path.GetDirectoryName(opt.Input) ?? "",
            Path.GetFileNameWithoutExtension(opt.Input) + "_256.png");

        imageFilter(opt.Input, output);

        Console.WriteLine(output);
    }

    static void imageFilter(string inputPath, string outputPath)
    {
        // 固定パラメータ
        const int Multiple = 256;
        const byte BgColor = 255;      // 白

        using var src = Cv2.ImRead(inputPath);

        int w = src.Width;
        int h = src.Height;
        int targetW = RoundUp(w, Multiple);
        int targetH = RoundUp(h, Multiple);
        int x = (targetW - w) / 2;
        int y = (targetH - h) / 2;

        // 元画像の型を維持した白キャンバス(RGBAでもOK、白+A=255)
        using var canvas = new Mat(new Size(targetW, targetH), src.Type(), Scalar.All(BgColor));

        // 貼り付け
        src.CopyTo(new Mat(canvas, new Rect(x, y, w, h)));


        Cv2.ImWrite(outputPath, canvas);
    }

    static int RoundUp(int value, int multiple)
        => ((value + multiple - 1) / multiple) * multiple;
}

ビルド

dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true /p:IncludeAllContentForSelfExtract=true /p:SelfContained=true --output "exeの出力先のディレクトリ"

実行コマンド

pad256 -i 2025-08-10193803.png

実行イメージ

元画像(386×293)

加工後(512×512)

コメント