【お知らせ】プログラミング記事の投稿はQiitaに移行しました。

画像処理

大量の画像を指定サイズに揃える必要に迫られました。縦横比を保ったままリサイズして、余った部分を切り落とします。こんな作業を一枚一枚フォトレタッチソフトでやるのは面倒なので、プログラムで一括処理しました。以下は主要部分の抜粋です。

リサイズ(高速・低品質)
public static Bitmap Resize(Image src, int width, int height)
{
    return new Bitmap(src, width, height);
} 
リサイズ(低速・高品質)
public static Bitmap Resize(Image src, int width, int height)
{
    Bitmap ret = new Bitmap(width, height);
    Graphics g = Graphics.FromImage(ret);
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.DrawImage(src, 0, 0, width, height);
    g.Dispose();
    return ret;
} 
切り抜き
public static Bitmap Cut(Image src, Rectangle r)
{
    Bitmap ret = new Bitmap(r.Width, r.Height);
    Graphics g = Graphics.FromImage(ret);
    g.DrawImage(src, 0, 0, r, GraphicsUnit.Pixel);
    g.Dispose();
    return ret;
} 
縦横比を維持したままリサイズして切り抜き
public static Bitmap Adjust(Image src, int width, int height)
{
    if (height == 0 || src.Height == 0) return null;
    double asp1 = (double)width / (double)height;
    double asp2 = (double)src.Width / (double)src.Height;
    int w = width, h = height;
    if (asp1 < asp2)
    {
        double zoom = (double)height / (double)src.Height;
        w = (int)(zoom * src.Width);
    }
    else
    {
        double zoom = (double)width / (double)src.Width;
        h = (int)(zoom * src.Height);
    }
    Bitmap bmp = Resize(src, w, h);
    Bitmap ret = Cut(bmp, new Rectangle(
        (w - width) / 2, (h - height) / 2, width, height));
    bmp.Dispose();
    return ret;
}