9951 explained code solutions for 126 technologies


php-gdHow to create thumbnail


<?php

$file = '/var/www/examples/heroine.png';
$size = getimagesize($file);
$im = imagecreatefrompng($file);

$w = 50;
$h = $w * $size[1] / $size[0];

$imf = imagecreatetruecolor($w, $h);
imagecopyresampled($imf, $im, 0,0,0,0, $w,$h,$size[0],$size[1]);

imagePng($imf, '/tmp/image.png');ctrl + c
/var/www/examples/heroine.png

path to image to resize

getimagesize

returns image size from given path

imagecreatefrompng

creates GD image object from given PNG image

50

width of resulting thumbnail

$w * $size[1] / $size[0]

calculate thumbnail height to keep aspect ratio

imagecopyresampled

resizes source image and writes result to destination image

imagePng

saves image in PNG format to the given path


How to create thumbnail, php gd

Usage example

<?php

$file = '/var/www/examples/heroine.png';
$size = getimagesize($file);
$im = imagecreatefrompng($file);

$w = 50;
$h = $w * $size[1] / $size[0];

$imf = imagecreatetruecolor($w, $h);
imagecopyresampled($imf, $im, 0,0,0,0, $w,$h,$size[0],$size[1]);

imagePng($imf, '/tmp/image.png');