【问题标题】:Resize image to maximum width or height in PHP without cropping在 PHP 中将图像大小调整为最大宽度或高度而不进行裁剪
【发布时间】:2017-03-12 11:56:11
【问题描述】:

我有一个向 PHP 表单处理程序发送 4 张图片的 AJAX 表单。可接受的格式为 .gif、.png、.jpg 或 .jpeg。在发送表单之前,我正在使用 javascript 检查图像文件类型。

现在,在 PHP 中我有以下代码:

    while($x <= 4) {
        $target_dir = "files/";
        $target_file = $target_dir . basename($_FILES["fileUpload".$x]["name"]);
        $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
        if (move_uploaded_file($_FILES["fileUpload".$x]["tmp_name"], $target_file)) {
                    $filename = date("d-m-Y---H-i-s---").rand(10000,99999);
                    $oldfile = $target_file;
                    $newfile = $target_dir . $filename . "." . $imageFileType;
                    rename($oldfile, $newfile);
                    $file[$x] = $filename . "." . $imageFileType;
                    $fileCounter++;
        }
      $x++;
    }

有些人会上传大图像文件,我想自动将它们调整为最大宽度/高度而不裁剪图像。如何使用 PHP 做到这一点?

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以为此使用 php GD 库。 在重命名函数后的 if 条件中,您可以编写以下代码:

    list($width, $height) = getimagesize($file);
    $ratio = $width / $height;
    if( $ratio > 1) {
        $resized_width = 500; //suppose 500 is max width or height
        $resized_height = 500/$ratio;
    }
    else {
        $resized_width = 500*$ratio;
        $resized_height = 500;
    }
    
        if ($imageFileType == 'png') {
            $image = imagecreatefrompng($newfile);
        } else if ($imageFileType == 'gif') {
            $image = imagecreatefromgif($newfile);
        } else {
            $image = imagecreatefromjpeg($newfile);
        }
    
    $resized_image = imagecreatetruecolor($resized_width, $resized_height);
    imagecopyresampled($resized_image, $image, 0, 0, 0, 0, $resized_width, $resized_height, $width, $height);
    

    【讨论】:

    • 也许在这里添加一个细节是 $imageFileType 可以通过执行类似这样的操作 $imageFileType = pathinfo($file, PATHINFO_EXTENSION);
    【解决方案2】:

    除非您之前检查过文件的大小,否则请尝试在 php 下使用 gzip 库

    if ($_FILES["fileToUpload"]["size"] > 500000)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 2017-12-08
      • 2014-05-03
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 2016-03-30
      相关资源
      最近更新 更多