Thursday, January 21, 2010

PHP - Dynamically resize an image without storing it

It is really a hassle to resize an image uploaded to be stored in different sizes, why not we resize it dynamically? Here I will show you how to generate an image with php for different sizes as we wish:

code:

<?php
$newwidth = $_GET["width"];
$newheight = $_GET["height"];
$image = $_GET["url"];
$ratio = ($_GET["ratio"] != "")? $_GET["ratio"] : "false";
$dst_x = ($_GET["dst_x"] != "")? intval($_GET["dst_x"]) : 0;
$dst_y = ($_GET["dst_y"] != "")? intval($_GET["dst_y"]) : 0;
$src_x = ($_GET["src_x"] != "")? intval($_GET["src_x"]) : 0;
$src_y = ($_GET["src_y"] != "")? intval($_GET["src_y"]) : 0;

$src = imagecreatefromjpeg($image);
list($width,$height)=getimagesize($image);
$newwidth = ($newwidth != "")? $newwidth : $width;
$newheight = ($newheight != "")? $newheight : $height;
if ($ratio == "true") {
$ratio_orig = $width/$height;
if ($newwidth/$newheight > $ratio_orig) {
$newwidth = $newheight*$ratio_orig;
} else {
$newheight = $newwidth/$ratio_orig;
}
}
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,$dst_x,$dst_y,$src_x,$src_y,$newwidth,$newheight,$width,$height);
imagejpeg($tmp);
header("Content-type: image/jpeg");
?>


How to use it :
-Save above as image.php
-Use it like : image.php?url=http://t2.gstatic.com/images?q=tbn:ZqzO2ew7hmrDJM%3Ahttp://farm3.static.flickr.com/2204/2403693037_0b63bdc4b4.jpg&width=100&height=100&ratio=true

1 comment:

kasehDANpercaya said...

yup. this approach is being use by wordpress.com blogs. however, this has toll on server.

to prevent this, you should put extra header to cache the generated image. at least, it wont be regenerated for the same user.