C#のWinFormsで画像を指定サイズに収まるように縮小

C# コンピュータ
C#

サムネイル用に縮小した画像が欲しいのです、指定サイズに収まるように画像を縮小するコードを書いてみました。
元画像の縦横比を保持したまま縮小し中央に配置するようにしてあります。

<div class="hcb_wrap"><pre class="prism line-numbers lang-txt" data-lang="Plan Text"><code>namespace syukusyou;

public partial class Form1 : Form
{
    /*
     画像を指定サイズに縮小する
    */
    static System.Drawing.Bitmap ResizeImage(System.Drawing.Image src, int width=384, int height=384)
    {
        // 戻り値用のBitmapオブジェクトの生成
        var result = new System.Drawing.Bitmap(width, height);
        // グラフィックオブジェクトを取得
        using var g = Graphics.FromImage(result);

        // 縦横の比率から縮小率を計算
        double fw = (double)width / (double)src.Width;
        double fh = (double)height / (double)src.Height;
        double scale = Math.Min(fw, fh);

        // 縮小後の幅と高さを計算
        int w2 = (int)(src.Width * scale);
        int h2 = (int)(src.Height * scale);

        // 縮小画像を中央に描画
        g.DrawImage(src, (width-w2)/2, (height-h2)/2, w2, h2);

        return result;
    }
    public Form1()
    {
        InitializeComponent();

        // 縮小する画像ファイルのパス
        const string imagePath = @&quot;H:\Pictures\202310190933-1.png&quot;;

        // 画像ファイルの読み込み
        var bmp = System.Drawing.Bitmap.FromFile(imagePath);

        // 縮小処理
        var smallBmp = ResizeImage(bmp);
        // 画像の破棄
        bmp.Dispose();

        // 縮小した画像を表示
        var picbox1 = new PictureBox {
            SizeMode = PictureBoxSizeMode.CenterImage,
            Dock = DockStyle.Fill,
            Image = smallBmp,
        };
        this.Controls.Add(picbox1);
    }
}
</code></pre></div>

実行すると以下の様に縮小された画像が表示されます。

コメント