Advertisemen
In this tutorial, we are going to learn how to create fixed size thumbnail using PHP. This is what you will be able to do after this tutorial.
First of all, create an empty php file and paste the following lines of code.
<?php
$filename = 'images/watch.jpg'; // 1
// 2
$w=300;
$h=300;
// Images
$org = imagecreatefromjpeg($filename);//3
$thumb = imagecreatetruecolor($w, $h); //4
// Scale & Copy
$x = imagesx($org);//5
$y = imagesy($org);
$scale = min($x / $w, $y / $h); //6
imagecopyresampled($thumb, $org, 0,0,
($x-($w*$scale))/2,($y-($h*$scale))/2,
$w, $h, $w * $scale, $h * $scale); //7
// Render out image ---- 8
header('Content-type: image/jpeg');
imagejpeg($thumb);
imagedestroy($org);
imagedestroy($thumb);
?>
$filename = 'images/watch.jpg'; // 1
// 2
$w=300;
$h=300;
// Images
$org = imagecreatefromjpeg($filename);//3
$thumb = imagecreatetruecolor($w, $h); //4
// Scale & Copy
$x = imagesx($org);//5
$y = imagesy($org);
$scale = min($x / $w, $y / $h); //6
imagecopyresampled($thumb, $org, 0,0,
($x-($w*$scale))/2,($y-($h*$scale))/2,
$w, $h, $w * $scale, $h * $scale); //7
// Render out image ---- 8
header('Content-type: image/jpeg');
imagejpeg($thumb);
imagedestroy($org);
imagedestroy($thumb);
?>
If you take a closer look at these codes, you will see some of the code has commented out number next to it. I will explain the codes number by number.
*1 This is the file path to the image where you save it in the server.*2 These are the width and height of the thumbnail that we are going to create. Change them according to your needs.
*3 This function creates new image from the file, see more here in php official website.
*4 This creates an empty image of given width and height.
*5 This function returns the width or height of the image.
*6 This function returns the lowest value between these two.
*7 That's where we crop an image, see more about this in here. If the provided image isn't in the square, it cut it proportionally to square because we provide width=300px and height = 300px then scales it down to the size of width=300px and height = 300px.
*8 these lines just render out image on the page.
Thanks
Please share if this tutorial is helpful to you.
Advertisemen
Tidak ada komentar:
Posting Komentar