Skip to content
Advertisement

Using imagejpeg() function to save image file

I am trying to upload the picture into two different directories and I would like to use the imagejpeg() function to put the picture in one of the directories. The two directories are called uploads and resized.

Here is my code to accomplish this:

$tmp_name = $_FILES["fileToUpload"]["tmp_name"];
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    imagejpeg($tmp_name,"resized/newimage.jpg");

    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} 

However, I keep getting the error imagejpeg() expects parameter 1 to be resource, string given in /home/sites/aejhyun.com/public_html/Syrian Project/upload.php on line 41. I also did some research by looking here http://php.net/manual/en/function.imagejpeg.php and http://php.net/manual/en/function.move-uploaded-file.php. However, I could not figure this problem out. Could anybody help?

Advertisement

Answer

You are setting string as $tmp_name and not an Image Resource itself , the function wants actual Image and not location or name of it , if you want to resize it , first you have to open it as Image then do whatever you want and finally save,

so , this is string

$tmp_name = $_FILES["fileToUpload"]["tmp_name"];

after you move it to $target_file you can open it as image

$image = imagecreatefromjpeg($target_file);

now you have Image itself and not just a file name and you can save it with imagejpeg

imagejpeg($image,"resized/newimage.jpg");
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement