PHP upload and resize image

taabouzeid picture taabouzeid · Jan 29, 2010 · Viewed 12.1k times · Source

I am working on a script that uploads a picture using PHP and I wanna make it resize the image to width 180 before saving it.
I tried using the WideImage library and ->saveFileTO(...) but when I include the WideImage.php in the page, the page goes blank !!
So here is my script if you can help me and tell me how to make it save the resized version

Answer

jschmier picture jschmier · Jan 29, 2010

You can use the PHP GD library to resize an image on upload.

The following code should give you an idea of how to implement the resize:

// Get the image info from the photo
$image_info = getimagesize($photo);
$width = $new_width = $image_info[0];
$height = $new_height = $image_info[1];
$type = $image_info[2];

// Load the image
switch ($type)
{
    case IMAGETYPE_JPEG:
        $image = imagecreatefromjpeg($photo);
        break;
    case IMAGETYPE_GIF:
        $image = imagecreatefromgif($photo);
        break;
    case IMAGETYPE_PNG:
        $image = imagecreatefrompng($photo);
        break;
    default:
        die('Error loading '.$photo.' - File type '.$type.' not supported');
}

// Create a new, resized image
$new_width = 180;
$new_height = $height / ($width / $new_width);
$new_image = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

// Save the new image over the top of the original photo
switch ($type)
{
    case IMAGETYPE_JPEG:
        imagejpeg($new_image, $photo, 100);
        break;
    case IMAGETYPE_GIF:
        imagegif($new_image, $photo);         
        break;
    case IMAGETYPE_PNG:
        imagepng($new_image, $photo);
        break;
    default:
        die('Error saving image: '.$photo);
}