【问题标题】:Resize image on upload, not after upload?上传时调整图像大小,而不是上传后?
【发布时间】:2017-04-30 17:10:07
【问题描述】:

我正在使用 HTML 和 PHP 上传图片。

<form action="" method="post">
    <input type="file" name="image" id="image">
</form>

如果图像大于 1500(宽度)x700(高度),我将如何使用 imagemagick 调整图像大小,以较大者为准,然后驻留图像。

据我所知,imagemagick 只能在上传后调整图像大小。是否可以在上传时调整图像大小然后存储到目录/文件夹中?

【问题讨论】:

    标签: php image upload imagemagick gd


    【解决方案1】:

    您可以调整临时文件的大小,然后在完成后保存文件。

    以下是我通常的处理方式。请注意,您需要做更多的工作来确保这一点!确保您正在检查允许上传的类型、大小等。

    我用这个函数来调整大小..

    function img_resize($target, $newcopy, $w, $h, $ext) {
    list($w_orig, $h_orig) = getimagesize($target);
    $scale_ratio = $w_orig / $h_orig;
    if (($w / $h) > $scale_ratio) {
        $w = $h * $scale_ratio;
    } else {
        $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    if ($ext == "gif"){ 
        $img = imagecreatefromgif($target);
    } else if($ext =="png"){ 
        $img = imagecreatefrompng($target);
    } else { 
        $img = imagecreatefromjpeg($target);
    }
    $tci = imagecreatetruecolor($w, $h);
    // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, 
    dst_h, src_w, src_h)
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
    imagejpeg($tci, $newcopy, 80);
    }
    

    然后我用临时文件调用函数..

     $fileName = $_FILES["image"]["name"]; // The file name
     $target_file = $_FILES["image"]["tmp_name"]; 
     $kaboom = explode(".", $fileName); // Split file name into an array using the dot
     $fileExt = end($kaboom); // Now target the last array element to get the file extension
     $fname = $kaboom[0];
     $exten = strtolower($fileExt);
    
     $resized_file = "uploads/newimagename.ext"; //need to change this make sure you set the extension and file name correct.. you will want to secure things up way more than this too..
     $wmax = 1500;
     $hmax = 700;
     img_resize($target_file, $resized_file, $wmax, $hmax, $exten);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多