优化 php 中的图像时未找到此类文件或目录

No such file or directory found while optimize the image in php

我正在上传图像和我正在优化的图像,但出现错误 "No such file or directory"。我收到以下代码的错误。

  $source_img =basename($_FILES["fileToUpload"]["name"]);

如果我写 $source_img = 'assets/img/login-bg.jpg'; 那么它就可以工作了。我想上传图片然后优化它。

我遇到错误

  Warning: getimagesize(demoimg.JPG): failed to open stream: No such file or directory in C:\xampp\htdocs\... on line 6

  Notice: Undefined variable: image in C:\xampp\htdocs\... on line 17

  Warning: imagejpeg() expects parameter 1 to be resource, null given in C:\xampp\htdocs\... on line 17

HTML

  <form action="" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload Image" name="submit">
  </form>

php

  function compress($source, $destination, $quality) {
  $info = getimagesize($source);
  if ($info['mime'] == 'image/jpeg') 
  $image = imagecreatefromjpeg($source);

  elseif ($info['mime'] == 'image/gif') 
  $image = imagecreatefromgif($source);

  elseif ($info['mime'] == 'image/png') 
  $image = imagecreatefrompng($source);

  imagejpeg($image, $destination, $quality);
  return $destination;
  }

  if(isset($_POST['submit'])){
  $source_img =basename($_FILES["fileToUpload"]["name"]);
  $temp = explode(".", $source_img);
  $newfilename = round(microtime(true)) . '.' . end($temp);
  $destination_img= "assets/$newfilename";

  $d = compress($source_img, $destination_img, 90);
  }

试试这个 php 代码:

<?php
    function compress($source, $destination, $quality) {
    $info = getimagesize($source);
    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);
    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);
    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);
    return $destination;
}

if(isset($_POST['submit'])){
    $source_img =$_FILES["fileToUpload"]["tmp_name"];
    $source_img_name =basename($_FILES["fileToUpload"]["name"]);
    $temp = explode(".", $source_img_name);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    $destination_img= "assets/$newfilename";

    $d = compress($source_img, $destination_img, 90);
}
?>

希望对您有所帮助。祝一切顺利!