14

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

我有这段代码并且知道缺少某些东西(但不知道是什么):

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 图像的比例?

我知道使用这种方法,但不知道把它放在哪里(!)。

4

2 回答 2

16

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

从那里,找到最大的属性并在此基础上按比例调整大小。

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

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

$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;
}
于 2009-04-01T02:53:01.337 回答
9

我认为您的代码很好,但是在我看来,将宽度和高度作为参数是您出错的地方。为什么这个方法的调用者必须决定他们想要多大的宽度和高度?我建议将其更改为百分比:

public bool ResizeImage(string fileName, string imgFileName,
    ImageFormat format, int percent)
{
    try
    {
        using (Image img = Image.FromFile(fileName))
        {
            int width = img.Width * (percent * .01);
            int height = img.Height * (percent * .01);
            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;
    }
}
于 2009-04-01T02:54:50.660 回答