Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to proportional resize image of any type in .NET?

Is possible to resize image proportionally in a way independent of the image type (bmp, jpg, png, etc)?

I have this code and know that something is missing (but don't know what):

public bool ResizeImage(string fileName, string imgFileName,
    ImageFormat format, int width, int height)
{
    try
    {
        using (Image img = Image.FromFile(fileName))
        {
            Image thumbNail = new Bitmap(width, height, img.PixelFormat);
            Graphics g = Graphics.FromImage(thumbNail);
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            Rectangle rect = new Rectangle(0, 0, width, height);
            g.DrawImage(img, rect);
            thumbNail.Save(imgFileName, format);
        }
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

If not possible, how can I resize proportional a jpeg image?

I know that using this method, but don't know where to put this (!).

like image 907
eKek0 Avatar asked Apr 01 '09 02:04

eKek0


1 Answers

First and foremost, you're not grabbing the CURRENT height and width of the image. In order to resize proportionately you'll need to grab the current height/width of the image and resize based on that.

From there, find the greatest attribute and resize proportionately based on that.

For instance, let's say the current image is 800 x 600 and you wanna resize proportionately within a 400 x 400 space. Grab the greatest proportion (800) and find it's ratio to the new size. 800 -> 400 = .5 Now take that ratio and multiply by the second dimension (600 * .5 = 300).

Your new size is 400 x 300. Here's a PHP example (sorry....you'll get it though)

$thumb_width = 400;
$thumb_height = 400;

$orig_w=imagesx($src_img); 
$orig_h=imagesy($src_img);      

if ($orig_w>$orig_h){//find the greater proportion
    $ratio=$thumb_width/$orig_w; 
    $thumb_height=$orig_h*$ratio;
}else{
    $ratio=$thumb_height/$orig_h; 
    $thumb_width=$orig_w*$ratio;
}
like image 193
jerebear Avatar answered Oct 19 '22 22:10

jerebear