Monday, May 17, 2010

PHP Resize Images


How to Resize Upload Images


Step 1:
Copy this code and save as upload-form.php

<?
//function of move_uploaded_file() use to upload images
$new_file_name=time().$_FILES["file"]["name"];
move_uploaded_file($_FILES["file"]["tmp_name"],"image/" . $new_file_name);
$uploaddir='image/';
?>

<!--This is upload form-->
<form action="upload-form.php" method="post"
enctype="multipart/form-data">
<p><label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<input type="submit" name="submit" value="Submit" /></p>
</form>
<?
$d_image=glob("image/*.*");//glob function use the read the image in image folder
for($row_count=0; $row_count < sizeof($d_image); $row_count++ ){
$name=$d_image[$row_count];
echo "<a href='$name'?rel='".thumbnail."'><img src= 'image-resize.php?src=".$name."&wmax=150&hmax=100&quality=90&bgcol=#FFFFFF'></a>";
}
?>

Step 2:
Copy this and save as image-resize.php

<?
header("Content-type: image/jpeg");
foreach($_REQUEST as $key=>$value){
$key=strtolower($key);
$$key=$value;
}
$source = imagecreatefromjpeg($src);
$orig_w=imagesx($source);
$orig_h=imagesy($source);

if ($orig_w>$wmax || $orig_h>$hmax)
{
$thumb_w=$wmax;
$thumb_h=$hmax;
if ($thumb_w/$orig_w*$orig_h>$thumb_h)
$thumb_w=round($thumb_h*$orig_w/$orig_h);
else
$thumb_h=round($thumb_w*$orig_h/$orig_w);
} else
{
$thumb_w=$orig_w;
$thumb_h=$orig_h;
}
if (!@$bgcol)
{
$thumb=imagecreatetruecolor($thumb_w,$thumb_h);
imagecopyresampled($thumb,$source,
0,0,0,0,$thumb_w,$thumb_h,$orig_w,$orig_h);
}
else
{
$thumb=imagecreatetruecolor($wmax,$hmax);
imagefilledrectangle($thumb,0,0,$wmax-1,$hmax-1,intval($bgcol,16));
imagecopyresampled($thumb,$source,
round(($wmax-$thumb_w)/2),round(($hmax-$thumb_h)/2),
0,0,$thumb_w,$thumb_h,$orig_w,$orig_h);
}
if (!@$quality) $quality=90;
imagejpeg($thumb,"",$quality);
imagedestroy($thumb);
?>


Tips : 1.Create folder call image for upload image.
2.Edit 'wmax' and 'hmax' in upload-form.php for change preview image size.



No comments: