0

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);
  }
Naren Verma
  • 2,205
  • 5
  • 38
  • 95
  • It's likely because the path is not included in the source, only the basename. You probably need to send the whole path to the file into your function, not just the basename. – Rasclatt Apr 30 '17 at 06:23
  • Thanks for replying Mr.Rasclatt. Actually, I am uploading Image from HTML and I am sending the only name of the image. How can I send the path? – Naren Verma Apr 30 '17 at 06:29

1 Answers1

1

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!

TutorialsBee
  • 101
  • 2
  • 5