Resize image upload into proportional dimensions using GD library


sometimes you want to manipulate images uploaded. A good way to do it is to resize the image to the max width or height, fill the background with transparency and yet keeping the same original width to height ratio. lets say we want a 300 x 300 pixel image.

$canvas = imagecreatetruecolor(300, 300);
            imagesavealpha($canvas, true);
            $alpha_channel = imagecolorallocatealpha($canvas, 0, 0, 0, 127);
            imagecolortransparent($canvas, $alpha_channel);
            imagefill($canvas, 0, 0, $alpha_channel);
            // process image width and height
            $old_x = imageSX($image);
            $old_y = imageSY($image);
            $thumb_x = 0;
            $thumb_y = 0;
            // say max width and height is 300px.
            if($old_x > $old_y)
            {
                $thumb_w =   300;
                $thumb_h =   $old_y*($thumb_w/$old_x);
                $thumb_y = abs(300 - $thumb_h) / 2;
            }
            if($old_x < $old_y)
            {
                $thumb_h =   300;
                $thumb_w =   $old_x*($thumb_h/$old_y);
                $thumb_x = abs(300 - $thumb_w) / 2;
            }
            if($old_x == $old_y)
            {
                $thumb_w    =   300;
                $thumb_h    =   300;
            }
            imagecopyresampled($canvas, $image, $thumb_x, $thumb_y, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
            imagesavealpha($canvas,true);

            // Move the file to the directory where logos are stored
            $logosDir = $this->container->getParameter('kernel.root_dir').'/../web/uploads/logos/';
            // write to file
            $fileName = md5(uniqid()).'.'.$file->guessExtension();
            imagepng($canvas, $logosDir.$fileName);
            imagedestroy($canvas);
Like it.? Share it:

Comments are closed.