【问题标题】:How do i resize image file to optional sizes如何将图像文件调整为可选大小
【发布时间】:2010-11-30 15:06:34
【问题描述】:

我有图片上传表单,用户附加一个图片文件,并选择图片大小来调整上传图片文件的大小(200kb、500kb、1mb、5mb、原始)。然后我的脚本需要根据用户的可选大小调整图像文件大小,但我不确定如何实现这个功能,

例如,用户上传一张 1mb 大小的图片,如果用户选择 200KB 来调整大小,那么我的脚本应该将其保存为 200kb 大小。

有没有人知道或有过类似任务的经验?

感谢您提前回复。

【问题讨论】:

    标签: php image image-scaling gd2


    【解决方案1】:

    对于GD library,使用imagecopyresampled()

    <?php
    // The file
    $filename = 'test.jpg';
    $percent = 0.5;
    
    // Content type
    header('Content-type: image/jpeg');
    
    // Get new dimensions
    list($width, $height) = getimagesize($filename);
    $new_width = $width * $percent;
    $new_height = $height * $percent;
    
    // Resample
    $image_p = imagecreatetruecolor($new_width, $new_height);
    $image = imagecreatefromjpeg($filename);
    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
    
    // Output
    imagejpeg($image_p, null, 100);
    ?>
    

    编辑:如果要将图像文件调整为指定的大小,那就有点困难了。所有主要的图像格式都使用压缩,压缩率因压缩内容的性质而异。压缩湛蓝的天空,你会得到比人海更好的压缩比。

    你能做的最好的就是尝试一个特定的大小是尝试一个特定的大小,看看文件大小是多少,必要时进行调整。

    Resize ratio = desired file size / actual file size
    Resize multipler = square root (resize ratio)
    New height = resize multiplier * actual height
    New width = resize multiplier * actual width
    

    这基本上是预期压缩比的近似值。我希望您会有一些容忍度(例如 +/- 5%),并且您可以根据需要调整数字。

    没有直接的方法可以将大小调整为特定的文件大小。最后我要补充一点,调整到特定文件大小是相当不寻常的。调整到特定的高度和/或宽度(保持纵横比)更为常见和预期(用户)。

    更新: 正如正确指出的那样,这会导致文件大小错误。该比率需要是文件大小比率的平方根,因为您要应用它两次(一次是高度,一次是宽度)。

    【讨论】:

    • 你最终会得到你想要的一半大小的文件,因为小数部分“调整大小比率”是平方的。如果你有一个 1MB 的图像并且你想要一个(大约)512KB 的文件,你想调整它的大小,以便 newheight = sqrt(2) * height(宽度也是如此)
    • 感谢您提供有用的 cmets
    【解决方案2】:

    使用 PHP 中提供的 GD 库:

    // $img is the image resource created by opening the original file
    // $w and $h is the final width and height respectively.
    $width = imagesx($img);$height = imagesy($img);
    $ratio = $width/$height;
    
    if($ratio > 1){
    // width is greater than height
    $nh = $h;
    $nw = floor($width * ($nh/$height));
    }else{
    $nw = $w;
    $nh = floor($height * ($nw/$width));
    }
    
    //centralize image
    $nx = floor(($nw- $w) / 2.0);
    $ny = floor(($nh-$h) / 2.0);
    
    $tmp2 = imagecreatetruecolor($nw,$nh);
    imagecopyresized($tmp2, $img,0,0,0,0,$nw,$nh,$width,$height);
    
    $tmp = imagecreatetruecolor($w,$h);
    imagecopyresized($tmp, $tmp2,0,0,$nx,$ny,$w,$h,$w,$h);
    
    imagedestroy($tmp2);imagedestroy($img);
    
    imagejpeg($tmp, $final_file);
    

    这段代码将获取原始图像,调整到指定尺寸。它将首先尝试按比例调整图像大小,然后裁剪 + 居中图像,使其完全符合指定的尺寸。

    【讨论】:

    • 我的意思是调整图像文件的大小,而不是图像本身的大小,例如,用户上传一个 1mb 大小的图像,如果用户选择 200KB 来调整大小,那么我的脚本应该将其保存为 200kb 大小。
    • 与其他答案一样,如果没有明确的答案来说明保存后的文件大小。
    猜你喜欢
    • 2014-03-23
    • 1970-01-01
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 2022-01-17
    • 2014-05-24
    相关资源
    最近更新 更多