phpimage-optimization

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


I am uploading the image and that image I am optimizing but I am getting the error "No such file or directory". I am getting the error on below code.

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

If I write $source_img = 'assets/img/login-bg.jpg'; then it is working. I want to upload image and then optimize it.

I am getting the error

  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);
  }

Solution

  • Try this php code:

    <?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);
    }
    ?>
    

    Hope it helps. All the Best!