0

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.

Theil
  • 101
  • 3
  • 11

3 Answers3

6

PHP comes built-in with the GD library.

There are many functions available for manipulating images however there's no need to re-invent the wheel.

Check out this gist for a simple image manipulation class - https://gist.github.com/880506

Here's an example usage...

$im = new ImageManipulator($_FILES['field_name']['tmp_name']);
$im->resample(640, 480); // resize to 640x480
$im->save('/path/to/destination/image.jpg', IMAGETYPE_JPEG);
Phil
  • 128,310
  • 20
  • 201
  • 202
1

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.

Theil
  • 101
  • 3
  • 11
0

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 http://us3.php.net/manual/en/function.imagecreate.php http://us3.php.net/manual/en/function.imagecopyresized.php

methodin
  • 6,473
  • 1
  • 21
  • 25