How to create Thumbnail Image in PHP without loosing its Original Quality using GD Library -
if(isset($_post["insert"])) { foreach($_files $imgfile) { $tmp_name = $imgfile['tmp_name']; $type = $imgfile['type']; $name = $imgfile['name']; //name of original image $size = $imgfile['size']; if (file_exists($tmp_name)) { if(is_uploaded_file($tmp_name)) { $target="realimage/"; $target .= basename($_files['image']['name']); //path of original image $file = fopen($tmp_name,'r'); $data = fread($file,filesize($tmp_name)); fclose($file); $data = chunk_split(base64_encode($data)); move_uploaded_file($tmp_name,$target); } $extension= explode(".", $target); $extension=$extension[count($extension)-1]; //gives image extension $maxwidth=400; $maxheight=200; switch($extension) { case 'gif': $tmpimg = imagecreatefromgif($target); break; case 'jpg': $tmpimg = imagecreatefromjpeg($target); break; case 'png': $tmpimg = imagecreatefrompng($target); break; } list($width,$height)=getimagesize($target); if($width > $height) { $thumb_width=$maxwidth; $thumb_height= intval($height*$thumb_width/$width); } else { $thumb_height= $maxheight; $thumb_width=intval($width*$thumb_height/$height); } $dest_x = intval(($maxwidth - $thumb_width) / 2); $dest_y = intval(($maxheight - $thumb_height) / 2); $newimg= imagecreatetruecolor($maxwidth,$maxheight); imagecopyresampled($newimg,$tmpimg,$dest_x,$dest_y,0,0,$thumb_width,$thumb_height,$width,$height); imagejpeg($newimg,"thumbimage/$name",100); } } }
the code 1) uploading image in folder "realimage" . 2) want display resized image of realimage on website . hav created folder "thumbimage" stores thumbnail image of original.
the code create thumbnails images larger specified thumbnail width , height, quality looses , blur images. want image quality same original image , size should small original.
i have got problem well, when upload image smaller specified thumbnail width & height , image not fit area , fills part of area leaving other area black.
help me in creating ideal thumbnail meeting scenarios.
try this:
$type = exif_imagetype($pathtoimages); $width = imagesx($img); $height = imagesy($img); // calculate thumbnail size if ($width >= $height) { //if width greater height $new_width = $thumbwidth; $new_height = floor($height * ($thumbwidth / $width)); } else { //if height greater width $new_height = $thumbwidth; $new_width = floor($width * ($thumbwidth / $height)); } // create new temporary image // echo $new_height; $tmp_img = imagecreatetruecolor($new_width, $new_height); imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // save thumbnail file switch($type) { case 1 : imagegif($tmp_img, $pathtothumbs . $file_name,90); break; case 2 : imagejpeg($tmp_img, $pathtothumbs . $file_name,90); break; case 3 : imagepng($tmp_img, $pathtothumbs . $file_name,90); break; case 6 : imagewbmp($tmp_img, $pathtothumbs . $file_name,90); break; }
Comments
Post a Comment