Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

c# - 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 (!).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...