How to resize an image without stretching – PHP

In order to resize an image without stretching, we will be calling built-in functions of PHP. No third party library will be used in this tutorial.

Resizing an image without stretching involves setting the new dimension of an image. You cannot decide both (width & height) of an image in order to resize without stretching. You will only tell the new dimension and this script will resize the image by maintaining its aspect ratio.

Get image and dimension

<form method="POST" action="resize.php" enctype="multipart/form-data">
    <p>
        <input type="file" name="file" onchange="onFileSelected();" id="image" accept="image/*" required="">
    </p>

    <p>
        <input type="number" name="enter_dimension" required="">
    </p>
    <input type="submit" name="submit">
</form>
  • enctype=”multipart/form-data” and method=”POST” are important in <form> tag
  • accept=”image/*” in <img> tag will allow you to view only images. Other documents will automatically be hidden.
  • onchange=”onFileSelected();” in <img> tag will be used to view the image before resizing (just for confirmation)

Show image preview

<img src="" id="preview">

<script type="text/javascript">
function onFileSelected() {
    var image = document.getElementById("image").files;
    if (image.length == 0) {
        console.log("Please select an image");
        return;
    }
    image = image[0];

    var reader = new FileReader();
    reader.onload = function (e) {
        document.getElementById('preview').setAttribute('src', e.target.result);
    }
    reader.readAsDataURL(image);
}
</script>

At this point, you will have something similar to the following:

Resizing image

Create a new file named “resize.php” (or it should be same as <form> tag action=”” attribute in step 1). First, you have to get the input dimension and user selected image:

<?php                        
$dimension = $_POST["enter_dimension"];                    
$file_name = $_FILES["file"]["tmp_name"];
    
$image_size = getimagesize($file_name);                        
$width = $image_size[0];    
$height = $image_size[1];
            
$ratio = $width / $height;                        
if ($ratio > 1)            
{
    $new_width = $dimension;
    $new_height = $dimension / $ratio;            
}            
else                        
{
    $new_height = $dimension;                    
    $new_width = $dimension * $ratio;            
}
                        
$src = imagecreatefromstring(file_get_contents($file_name));                        
$destination = imagecreatetruecolor($new_width, $new_height);

imagecopyresampled($destination, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height);                        
imagepng($destination, $file_name);
        
imagedestroy($src);                        
imagedestroy($destination);
            
move_uploaded_file($file_name, $_FILES["file"]["name"]);                        
echo "<img src='" . $_FILES["file"]["name"] . "' />";

Explanation

  • getimagesize: This function returns an array containing the width and height of the image.
  • imagecreatefromstring: It creates a new image from image file data.
  • imagecreatetruecolor: It just accepts width and heigth as parameters. And return the true color of the image.
  • imagecopyresampled: This function copies the image from source to destination. And also resize the image with provided width and height.
  • imagepng: This outputs the PNG image to the browser if the 2nd parameter is not provided. But since we provided the 2nd parameter, so it will save the image in a separate PNG file.
  • imagedestroy: Simply destroys the image object.

[wpdm_package id=’81’]