php image resize code example

Example 1: resize image html

<!--
Resize image using html 

When we add any image in 'src' attribute of 'img' tag then image appears with original size on webpage
and if we want to resize the image we have to add extra attribute i.e. height and width to img tag to resize the image
-->

Simple img tag
<img src="image_path" alt="Image Sample">

With height and width attribute
<img src="image_path" width="200" height="40" alt="Image Sample">

<!--
I hope it will help you.
Namaste
Stay Home Stay Safe
-->

Example 2: php resize image

// resize on upload
$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
    $target_filename = $file_name;
    $ratio = $width/$height;
    if( $ratio > 1) {
        $new_width = $maxDim;
        $new_height = $maxDim/$ratio;
    } else {
        $new_width = $maxDim*$ratio;
        $new_height = $maxDim;
    }
    $src = imagecreatefromstring( file_get_contents( $file_name ) );
    $dst = imagecreatetruecolor( $new_width, $new_height );
    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    imagedestroy( $src );
    imagepng( $dst, $target_filename ); // adjust format as needed
    imagedestroy( $dst );
}

Example 3: php rotate image

After some INet searches and personal try-and-failures I succeed to rotate PNG images with preserving alpha channel transparency (semi transparency).

<?php
    $filename = 'YourFile.png';
    $rotang = 20; // Rotation angle
    $source = imagecreatefrompng($filename) or die('Error opening file '.$filename);
    imagealphablending($source, false);
    imagesavealpha($source, true);

    $rotation = imagerotate($source, $rotang, imageColorAllocateAlpha($source, 0, 0, 0, 127));
    imagealphablending($rotation, false);
    imagesavealpha($rotation, true);

    header('Content-type: image/png');
    imagepng($rotation);
    imagedestroy($source);
    imagedestroy($rotation);
?>

Example 4: php resize

Class resize
{
    // *** Class variables
    private $image;
    private $width;
    private $height;
 
    function __construct($fileName)
    {
        // *** Open up the file
        $this->image = $this->openImage($fileName);
 
        // *** Get width and height
        $this->width  = imagesx($this->image);
        $this->height = imagesy($this->image);
    }
}

Tags:

Html Example