Jump to content

Can you take a look at this image upload code and tell me what's wrong with it?


Recommended Posts

I have an image upload script where I am trying to compress an image to a lower file size. The code works. The image uploads to the directory with the correct name as intended. The only thing is that it's not compression the image as it should be. The size of the new image is the same as the old image. 

Here's my code. Can you spot what i'm doing wrong?

// FUNCTION FOR COMPRESSION
function compress_image($source_url, $destination_url, $quality) {

  $info = getimagesize($source_url);

  if($info['mime'] == 'image/jpeg') {

    $image = imagecreatefromjpeg($source_url);

  } else if ($info['mime'] == 'image/gif') {

    $image = imagecreatefromgif($source_url);

  } else if ($info['mime'] == 'image/png') {

    $image = imagecreatefrompng($source_url);
    imagejpeg($image, $destination_url, $quality);

  }
  return $destination_url;
}

// FORM SUBMIT CODE

$errors = array();
$db->beginTransaction();

if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) {
  if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) {
	
    // GENERATES A 10 CHARACTER STRING TO BE USED FOR AN IMAGE NAME
    $random_name   =	generateRandomString(10);
	
	$global_user_id = 10;
	$url_project_id = 5;

    $target_dir	   = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';
    $target_file   = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk      = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if(!is_dir($target_dir)){
      mkdir($target_dir, 0775, true);
    }

    // RESIZE IMAGE
    $pathname      = $_FILES["fileToUpload"]["tmp_name"];
    $resized_image = compress_image($pathname, $random_name, 40);
    $new_file_path = $target_dir . $resized_image . '.' . $imageFileType;

    // Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
     //   echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        $errors[] = 'File is not an image!';
        $uploadOk = 0;
    }
    // Check if file already exists
    if (file_exists($new_file_path)) {
        $errors[] = 'Sorry, file already exists!';
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        $errors[] = 'Sorry, your file size is bigger than 5mb!';
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") {
        $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!';
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if($uploadOk == 0) {
        $errors[] = 'Sorry, your file was not uploaded!';
    // if everything is ok, try to upload file
    } else {

      if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_file_path)) {

        // SUCCESS MESSAGE

      } else {
        $errors[] = 'Sorry, there was an error uploading your file!';
      }
    }
  } else {
    $errors[] = 'You must upload an image!';
  }
}

if(empty($errors)) {
  $db->commit();

  header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
  exit;

} else {
 $db->rollBack();
}

 

Step away from your computer for the rest of the day. Or at least stop looking at your code for a while. Come back to it tomorrow.

Then go through your form processing code line by line and say, out loud to yourself (or maybe to a duck), what it does. Think about where the files are and what you're doing with them each step of the way.

2 hours ago, requinix said:

Step away from your computer for the rest of the day. Or at least stop looking at your code for a while. Come back to it tomorrow.

Then go through your form processing code line by line and say, out loud to yourself (or maybe to a duck), what it does. Think about where the files are and what you're doing with them each step of the way.

I have tried many different variations of the code. Some work and some don't. But none of the solutions gets me a compressed image. And I doubt I am going to figure out this particular solution by stepping away from the computer. I have already spent hours on it. Posting on this forum is my last resort. 

1 hour ago, imgrooot said:

And I doubt I am going to figure out this particular solution by stepping away from the computer. I have already spent hours on it.

The whole point of stepping away from the computer is so that you stop trying to figure it out. Your brain needs to stop working on this and do something else.

Because maybe tomorrow, when you come at it fresh, you'll see (a) how compress_image is getting something particularly wrong and (b) where your files are actually going.

7 hours ago, requinix said:

Your brain needs to stop working on this and do something else.

This is a real thing how the brain works. It has to do with how the prefrontal cortex works. I have solved many a problem by not trying to solve the problem and stepping away from it. Without trying, you get that A-ha moment and the answer comes to you.

Normally I would agree with you but this problem is little more complex than my brain can handle.  I had a good night's rest and still I don't see the solution.

Let me walk you through to my thoughts. This is a bit different method than my original code.

// RETRIEVING THE DIRECTORY WHERE THE IMAGES ARE LOCATED
$target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

// RETRIEVING THE EXTENSION OF THE IMAGE. E.G. JPG
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// THE SOURCE IMAGE I AM UPLOAD. E.G. php4AC9.tmp 
$source_image = $_FILES["fileToUpload"]["tmp_name"];

// INSTEAD OF USING THE ORIGINAL NAME, I AM GENERATING A NEW NAME FOR EACH IMAGE I UPLOAD. e.g. Dbo9PxcZi6
$random_name = generateRandomString(10);

// THIS WOULD GENERATE A NEW NAME FOR THE IMAGE. E.G. Dbo9PxcZi6.jpg
$destination_image = $random_name . '.' . $imageFileType;

// THIS COMPRESSES THE IMAGE USING THE SOURCE IMAGE AND THE DESTINATION IMAGE.
$resized_image = compress_image($source_image, $destination_image, 50);

// NEW FILE PATH FOR THE IMAGE UPLOAD. E.G. ../members/images/7/projects/8/Dbo9PxcZi6.jpg
$new_file_path = $target_dir . $resized_image;

// CHECKS IF THE IMAGE HAS BEEN UPLOADED TO THE DIRECTORY
if(move_uploaded_file($source_image, $new_file_path)) {
 // SUCCESS
}

 

So now that you know my thought process, could you please point out exactly what I am doing wrong? I don't want to keep beating around the bush.

19 minutes ago, requinix said:

Fair enough. Two questions:

1. What type of image are you testing with?
2. Where are you looking to see the compressed image?

1. For now I am only testing jpeg images. The image I'm testing with is 1.64mb in size.

2. Not sure I understand this question.

 

The compression function I am using is based on these two tutorials.  Maybe it'll give you an insight on what I'm trying to do.

https://makitweb.com/how-to-compress-image-size-while-uploading-with-php/

https://www.johnpatel.com/compress-images-in-php/ 

12 minutes ago, imgrooot said:

1. For now I am only testing jpeg images. The image I'm testing with is 1.64mb in size.

Alright. Now look at your compress_image function and tell me if you see anything wrong with it.

12 minutes ago, imgrooot said:

2. Not sure I understand this question.

Nevermind, this question is no longer relevant given your answer to the first one.

27 minutes ago, requinix said:

Alright. Now look at your compress_image function and tell me if you see anything wrong with it.

Nevermind, this question is no longer relevant given your answer to the first one.

Here is the updated function. I moved the imagejpeg line outside the elseif statement. Still the same issue. Image not compressing. 

function compress_image($source_url, $destination_url, $quality) {

  $info = getimagesize($source_url);

  if($info['mime'] == 'image/jpeg') {

    $image = imagecreatefromjpeg($source_url);

  } else if ($info['mime'] == 'image/gif') {

    $image = imagecreatefromgif($source_url);

  } else if ($info['mime'] == 'image/png') {

    $image = imagecreatefrompng($source_url);

  } else {}

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

 

I found another compress function that's a little more sophisticated. It uploads the file successfully. But once again it doesn't compress the image. I'm thinking perhaps something is wrong with my original setup? I really need to know exactly what it is instead of hints. I've been at it for over a day and still no luck.

function compressImage($source_url, $destination_url, $quality) {

    //$quality :: 0 - 100
    $info = getimagesize($source_url);

    if($destination_url == NULL || $destination_url == "" )  {

      $destination_url = $source_url;

      $info = getimagesize($source_url);

    } else if($info['mime'] == 'image/jpeg' || $info['mime'] == 'image/jpg') {

        $image = imagecreatefromjpeg($source_url);
        //save file
        //ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default is the default IJG quality value (about 75).
        imagejpeg($image, $destination_url, $quality);

        //Free up memory
        imagedestroy($image);

    } else if($info['mime'] == 'image/png') {

        $image = imagecreatefrompng($source_url);

        imageAlphaBlending($image, true);
        imageSaveAlpha($image, true);

        /* chang to png quality */
        $png_quality = 9 - round(($quality / 100 ) * 9 );
        imagePng($image, $destination_url, $png_quality);//Compression level: from 0 (no compression) to 9(full compression).
        //Free up memory
        imagedestroy($image);

    } else {
        return FALSE;
    }

    return $destination_url;

}

 

The compression function is not the problem. Anymore. After you moved that imagejpeg line.

So now let's go back to an earlier question: where do you expect the images to go? Have you been looking in the same directory as the PHP script?

50 minutes ago, requinix said:

The compression function is not the problem. Anymore. After you moved that imagejpeg line.

So now let's go back to an earlier question: where do you expect the images to go? Have you been looking in the same directory as the PHP script?

I expect the images to go to this directory.

$target_dir = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';

And they do go to this directory. I see the images being uploaded with the correct name and extension. The only thing not happening is that those images are not being reduced in file size. They are the exact same size as the original image.

Just to clarify, by compressing an image, I meant reducing the image file size. So if the original image file size is 1.6mb, then I want to reduce/compress that to a lower file size and upload it to the directory. I am assuming that's what that function does, unless I am wrong.

Alright so someone else was able to point out what I was doing wrong. 

The issue with was this line. I was uploading the original file, which I assumed was needed as the source.

if(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $new_file_path)) {

The fix is this to change it to this.

if(rename($new_image, $new_file_path)) {

 

Here is my full code. It works now.

if(isset($_FILES['fileToUpload']) AND !empty($_FILES['fileToUpload']["name"])) {
  if(is_uploaded_file($_FILES['fileToUpload']["tmp_name"])) {

    $target_dir	   = '../members/images/'.$global_user_id.'/projects/'.$url_project_id.'/';
    $target_file   = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    $source_file   = $_FILES["fileToUpload"]["tmp_name"];
    $random_name   = generateRandomString(10);
    $new_image     = $random_name . '.' . $imageFileType;
    $resized_image = compress_image($source_file, $new_image, 10);
    $new_file_path = $target_dir . $resized_image;

    if(!is_dir($target_dir)){
      mkdir($target_dir, 0775, true);
    }

    $uploadOk      = 1;
    // Check if image file is a actual image or fake image
    $check = getimagesize($source_file);
    if($check !== false) {
     //   echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        $errors[] = 'File is not an image!';
        $uploadOk = 0;
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        $errors[] = 'Sorry, file already exists!';
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 5000000) {
        $errors[] = 'Sorry, your file size is bigger than 5mb!';
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "JPG" && $imageFileType != "PNG" && $imageFileType != "JPEG" && $imageFileType != "GIF") {
        $errors[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed!';
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if($uploadOk == 0) {
        $errors[] = 'Sorry, your file was not uploaded!';
    // if everything is ok, try to upload file
    } else {

      if(rename($new_image, $new_file_path)) {

        echo 'success';

      } else {
        $errors[] = 'Sorry, there was an error uploading your file!';
      }
    }
  } else {
    $errors[] = 'You must upload an image!';
  }
}

 

Edited by imgrooot
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.