Resize images in PHP without using third-party libraries?

Solution 1:

Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.

$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

copy($_FILES, $resizedDestination);

$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];

$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

$originalImage = imageCreateFromJPEG($image);

$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);

imageDestroy($originalImage);
imageDestroy($resizedImage);

To anyone else seeking a complete example, create two files:

<!-- send.html -->

<html>

<head>

    <title>Simple File Upload</title>

</head>

<body>

    <center>

        <div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">

            Select an image.

            <br/>
            <br/>

            <form action="receive.php" enctype="multipart/form-data" method="post">
                <input type="file" name="image" size="40">
                <input type="submit" value="Send">
            </form>

        </div>

    </center>

</body>

<?php

// receive.php

$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";

echo "File path:".$filePath."<br/>";

if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {

    echo "File successfully received through HTTP POST.<br/>";

    // Validate the file size, accept files under 5 MB (~5e+6 bytes).

    if ($_FILES['image']['size'] <= 5000000) {

        echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";

        // Resize and save the image.

        $image = $_FILES["image"]["tmp_name"];
        $resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";

        copy($_FILES, $resizedDestination);

        $imageSize = getImageSize($image);
        $imageWidth = $imageSize[0];
        $imageHeight = $imageSize[1];

        $DESIRED_WIDTH = 100;
        $proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);

        $originalImage = imageCreateFromJPEG($image);

        $resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);

        imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
        imageJPEG($resizedImage, $resizedDestination);

        imageDestroy($originalImage);
        imageDestroy($resizedImage);

        // Save the original image.

        if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {

            echo "Copied the original file to the specified destination.<br/>";

        }

    }

}

?>

Solution 2:

I made a small function to resize images, the function is below:

function resize_image($path, $width, $height, $update = false) {
   $size  = getimagesize($path);// [width, height, type index]
   $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
   if ( array_key_exists($size['2'], $types) ) {
      $load        = 'imagecreatefrom' . $types[$size['2']];
      $save        = 'image'           . $types[$size['2']];
      $image       = $load($path);
      $resized     = imagecreatetruecolor($width, $height);
      $transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
      imagesavealpha($resized, true);
      imagefill($resized, 0, 0, $transparent);
      imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
      imagedestroy($image);
      return $save($resized, $update ? $path : null);
   }
}

And here's how you use it:

if ( resize_image('dir/image.png', 50, 50, true) ) {// resize image.png to 50x50
   echo 'image resized!';
}

Solution 3:

there is 1 very simple image re-size function for all image types that keeps transparency and is very easy to use

check out :

https://github.com/Nimrod007/PHP_image_resize

hope this helps

Solution 4:

ImageMagick is the fastest and probably the best way to resize images in PHP. Check out different examples here. This sample shows how to resize and image on upload.

Solution 5:

Thanks to Mateus Nunes! i edited his work a bit to get transparent pngs working:

$source         = $_FILES["..."]["tmp_name"];
$destination    = 'abc/def/ghi.png';
$maxsize        = 45;

$size = getimagesize($source);
$width_orig = $size[0];
$height_orig = $size[1];
unset($size);
$height = $maxsize+1;
$width = $maxsize;
while($height > $maxsize){
    $height = round($width*$height_orig/$width_orig);
    $width = ($height > $maxsize)?--$width:$width;
}
unset($width_orig,$height_orig,$maxsize);
$images_orig    = imagecreatefromstring( file_get_contents($source) );
$photoX         = imagesx($images_orig);
$photoY         = imagesy($images_orig);
$images_fin     = imagecreatetruecolor($width,$height);
imagesavealpha($images_fin,true);
$trans_colour   = imagecolorallocatealpha($images_fin,0,0,0,127);
imagefill($images_fin,0,0,$trans_colour);
unset($trans_colour);
ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
unset($photoX,$photoY,$width,$height);
imagepng($images_fin,$destination);
unset($destination);
ImageDestroy($images_orig);
ImageDestroy($images_fin);