如何在 .NET 中按比例调整任何类型的图像? [英] How to proportional resize image of any type in .NET?

查看:23
本文介绍了如何在 .NET 中按比例调整任何类型的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以以独立于图像类型(bmp、jpg、png 等)的方式按比例调整图像大小?

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

如果不可能,我如何调整 jpeg 图像的比例?

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

推荐答案

首先,您没有获取图像的当前高度和宽度.为了按比例调整大小,您需要获取图像的当前高度/宽度并基于此调整大小.

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.

例如,假设当前图像是 800 x 600,并且您想在 400 x 400 的空间内按比例调整大小.获取最大的比例 (800) 并找到它与新尺寸的比例.800 -> 400 = .5 现在采用该比率并乘以第二个维度 (600 * .5 = 300).

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).

您的新尺寸为 400 x 300.这是一个 PHP 示例(抱歉......你会明白的)

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

这篇关于如何在 .NET 中按比例调整任何类型的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆