How to Resize images in php

  • November 10, 2015
  • cboursinos
  • php
  • Comments Off on How to Resize images in php

Many websites need to upload images and manipulated them to fit inside they boxes. 
An easy way to resize images in PHP is the following code, that create images taking as parameter the file name and the width that you
want to give to the new image. 

resize_and_optimization

First of all you need to install php5-gd to take advantage of the custom functions that it has. 
After copy paste the function 
    public function ResizeImage($filename, $width_size){
        $path_parts = pathinfo($filename);
        $new_filename = $path_parts['dirname']."/".$path_parts['filename']."_".$width_size.".jpg";

        list($width, $height) = getimagesize($filename);
        if ($width>$width_size) {
//            header('Content-Type: image/jpeg');
            $newwidth = $width_size;
            $newheight = round(($height * $width_size) / $width);

            $thumb = imagecreatetruecolor($newwidth, $newheight);
            $source = imagecreatefromjpeg($filename);
            imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

            // Output and free memory
            //the resized image will be 400x300
            imagejpeg($thumb, $new_filename);
            imagedestroy($thumb);
            return true;
        } else {
            return false;
        }
    }

and that's it, you can create as many as photos that you want with whatever width you want. 

Cheers guys 
Knowledge are for every one