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/ Project/upload.php on line 41. I also did some research by looking here and . However, I could not figure this problem out. Could anybody help?

2

2 Answers

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

This worked for me

$url = 'my_img_url.jpeg';
$binary = imagecreatefromstring(file_get_contents($url));
imageJpeg($binary, "myimage.jpg", 100);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest