【问题标题】:how to crop image before upload using php?如何在使用 php 上传之前裁剪图像?
【发布时间】:2020-05-26 21:45:06
【问题描述】:

我一直在寻找一种在上传照片之前调整照片大小的方法,我找到了下面的代码,它完全符合我的目标,只是希望它不要将原始图像与裁剪后的图像一起存储在目录中。我对其进行了一些更改,但没有成功。我希望我能得到一些帮助。

  if(isset($_POST["submit"])) {
      if(is_array($_FILES)) {


    $uploadedFile = $_FILES['file']['tmp_name']; 
    $sourceProperties = getimagesize($uploadedFile);
    $newFileName = time();
    $dirPath = "uploads/";
    $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
    $imageType = $sourceProperties[2];


    switch ($imageType) {


        case IMAGETYPE_PNG:
            $imageSrc = imagecreatefrompng($uploadedFile); 
            $tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
            imagepng($tmp,$dirPath. $newFileName. "_thump.". $ext);
            break;           

        case IMAGETYPE_JPEG:
            $imageSrc = imagecreatefromjpeg($uploadedFile); 
            $tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
            imagejpeg($tmp,$dirPath. $newFileName. "_thump.". $ext);
            break;

        case IMAGETYPE_GIF:
            $imageSrc = imagecreatefromgif($uploadedFile); 
            $tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
            imagegif($tmp,$dirPath. $newFileName. "_thump.". $ext);
            break;

        default:
            echo "Invalid Image type.";
            exit;
            break;
    }


    move_uploaded_file($uploadedFile, $dirPath. $newFileName. ".". $ext);
    echo "Image Resize Successfully.";
    }
  }


   function imageResize($imageSrc,$imageWidth,$imageHeight) {

    $newImageWidth =900;
    $newImageHeight =534;

     $newImageLayer=imagecreatetruecolor($newImageWidth,$newImageHeight);



   imagecopyresampled($newImageLayer,$imageSrc,0,0,0,0,$newImageWidth,$newImageHeight,$imageWidth,$imageHeight);

    return $newImageLayer;
}
?> 

【问题讨论】:

    标签: php function file post image-resizing


    【解决方案1】:

    如果您从代码中删除move_uploaded_file 行,它将不会保存原始文件(它将保留在临时文件夹中并最终被系统删除)。您的其余代码应该按原样工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-28
      • 2017-08-05
      • 1970-01-01
      • 2020-12-24
      • 2021-09-04
      • 1970-01-01
      • 2015-02-22
      • 2011-07-14
      相关资源
      最近更新 更多