在 PHP 中调整图像大小

2023-11-24

我想编写一些 PHP 代码,自动将通过表单上传的任何图像大小调整为 147x147px,但我不知道如何去做(我是一个相对 PHP 新手)。

到目前为止,我已经成功上传图像,识别文件类型并清理名称,但我想将调整大小功能添加到代码中。例如,我有一个 2.3MB、尺寸为 1331x1331 的测试图像,我希望代码能够缩小它的大小,我猜这也会显着压缩图像的文件大小。

到目前为止,我已经得到以下内容:

if ($_FILES) {
    //Put file properties into variables
    $file_name = $_FILES['profile-image']['name'];
    $file_size = $_FILES['profile-image']['size'];
    $file_tmp_name = $_FILES['profile-image']['tmp_name'];
    
    //Determine filetype
    switch ($_FILES['profile-image']['type']) {
        case 'image/jpeg': $ext = "jpg"; break;
        case 'image/png': $ext = "png"; break;
        default: $ext = ''; break;
    }
    
    if ($ext) {
        //Check filesize
        if ($file_size < 500000) {
            //Process file - clean up filename and move to safe location
            $n = "$file_name";
            $n = ereg_replace("[^A-Za-z0-9.]", "", $n);
            $n = strtolower($n);
            $n = "avatars/$n";
            move_uploaded_file($file_tmp_name, $n);
        } else {
            $bad_message = "Please ensure your chosen file is less than 5MB.";
        }
    } else {
        $bad_message = "Please ensure your image is of filetype .jpg or.png.";
    }
}

$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);

您需要使用 PHP图像魔术师 or GD处理图像的函数。

以 GD 为例,它就像这样简单......

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*abs($r-$w/$h)));
        } else {
            $height = ceil($height-($height*abs($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefromjpeg($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

你可以调用这个函数,就像这样......

$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);

从个人经验来看,GD 的图像重采样也确实显着减小了文件大小,尤其是在对原始数码相机图像进行重采样时。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 PHP 中调整图像大小 的相关文章