Feedback

„Zoom“ für System.Drawing.Image

Sprache: C#

Manchmal braucht man (oder zumindest ich) eine Funktion um Bilder – dem ImageLayout 'Zoom' entsprechend – zu vergrößern. Sprich so, dass die Seitenverhältnisse beibehalten werden. Beispiel: Man hat ein Label 'myLabel'. Dort soll ein beliebig großes Bild (Image-Eigenschaft) drauf abgebildet werden: [code]myLabel.Image = new Bitmap("myImage.jpg").Zoom(myLabel.Size);[/code]
public static class ExtensionMethods
{
    public static Bitmap Zoom(this Image img, Size max)
    {
        double factorHo = (double)max.Width / (double)img.Width;
        double factorVe = (double)max.Height / (double)img.Height;
        double factor = GetSmaller(factorHo, factorVe);
        return new Bitmap(img, new Size((int)(img.Width * factor), (int)(img.Height * factor)));
    }

    private static double GetSmaller(double n1, double n2)
    {
        if (n1 < n2)
            return n1;
        else
            return n2;
    }
}
public static class ExtensionMethods
{
    public static Bitmap Zoom(this Image img, Size max)
    {
        double factorHo = (double)max.Width / (double)img.Width;
        double factorVe = (double)max.Height / (double)img.Height;
        double factor = GetSmaller(factorHo, factorVe);
        return new Bitmap(img, new Size((int)(img.Width * factor), (int)(img.Height * factor)));
    }

    private static double GetSmaller(double n1, double n2)
    {
        if (n1 < n2)
            return n1;
        else
            return n2;
    }
}