Theil
Theil

Reputation: 101

Resize image on server

I made a file that is in charge of uploading images, this images are then moved to a folder in the server. I think I can't resize the image directly in the $_FILES array so I think I must resize the image after being in the server, so my question is, how can I resize images that are in the server?

This is part of the code I have:

//This is after getting target which is the file saved on the server

move_uploaded_file($_FILES[$str]['tmp_name'], $target);

scale_image($target);

Now the function scale_image()

function scale_image($image)
{

    if(!empty($image)) //the image to be uploaded is a JPG I already checked this
    {
        $source_image = imagecreatefromjpeg($image);
        $source_imagex = imagesx($source_image);
        $source_imagey = imagesy($source_image);

        $dest_imagex = 300;
        $dest_imagey = 200;

        $image = imagecreatetruecolor($dest_imagex, $dest_imagey);
        imagecopyresampled($image, $source_image, 0, 0, 0, 0,
        $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);

    }
}

But this doesn't seems to work, it moved the file but not resized.

Upvotes: 0

Views: 8076

Answers (2)

Theil
Theil

Reputation: 101

I wasn't creating a file to the server's dir so this is what I did move_uploaded_file($_FILES[$str]['tmp_name'], $target); scale_image($target,$target);

Now the function scale_image()

function scale_image($image,$target)
{
  if(!empty($image)) //the image to be uploaded is a JPG I already checked this
  {
     $source_image = imagecreatefromjpeg($image);
     $source_imagex = imagesx($source_image);
     $source_imagey = imagesy($source_image);

     $dest_imagex = 300;
     $dest_imagey = 200;

     $image2 = imagecreatetruecolor($dest_imagex, $dest_imagey);
     imagecopyresampled($image2, $source_image, 0, 0, 0, 0,
     $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);

     imagejpeg($image2, $target, 100);

  }
}

Thank you all very much, the resource you gave me helped me to create this function.

Upvotes: 1

methodin
methodin

Reputation: 6712

Move the uploaded file to a tmp directory (use tmp_name in $_FILES for original location), read it in using gd, resize then save it to the final directory.

http://php.net/manual/en/function.move-uploaded-file.php https://www.php.net/manual/en/function.imagecreate.php https://www.php.net/manual/en/function.imagecopyresized.php

Upvotes: 0

Related Questions