Code Snippet – C#: Generate square thumbnails

To generate a square thumbnail in c#, use this code:

public Bitmap Generate75x75Pixel(Bitmap image) {
    if(image == null)
    throw new ArgumentNullException("image");
    Bitmap bmp = null;
    Bitmap crapped = null;
    int x = 0, y = 0;
    double prop = 0;
    if(image.Width > 75) {
        // compute proportation
        prop = (double)image.Width / (double)image.Height;
        if(image.Width > image.Height) {
            x = (int)Math.Round(75 * prop, 0);
            y = 75;
        }
        else {
            x = 75;
            y = (int)Math.Round(75 / prop, 0);
        }
        bmp = new Bitmap((Image)image, new Size(x, y));
        crapped = new Bitmap(75, 75);
        Graphics g = Graphics.FromImage(crapped);
        g.DrawImage(bmp,
            new Rectangle(0, 0, 75, 75),
            new Rectangle(0, 0, 75, 75),
            GraphicsUnit.Pixel
        );
        bmp = crapped;
    }
    else {
        crapped = image;
    }
    return bmp;
}

Von vandango

Mein Name ist Jonathan Naumann. Mein Nick ist vandango. Ich lebe in Bremen, das liegt im Norden Deutschlands.