用GD库生成高质量的缩略图片

http://tech.ddvip.com   2008年09月06日    社区交流

内容摘要:GD库在php中的应用是很广泛的,本文笔者用实例程序来说明如何用GD库和php程序来控制图片。

  1. <? 
  2. 
  3. $FILENAME="image_name"; 
  4. 
  5. // 生成图片的宽度 
  6. $RESIZEWIDTH=400; 
  7. 
  8. // 生成图片的高度 
  9. $RESIZEHEIGHT=400; 
 10. 
 11. 
 12. function ResizeImage($im,$maxwidth,$maxheight,$name){ 
 13.   $width = imagesx($im); 
 14.   $height = imagesy($im); 
 15.   if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){ 
 16.     if($maxwidth && $width > $maxwidth){ 
 17.       $widthratio = $maxwidth/$width; 
 18.       $RESIZEWIDTH=true; 
 19.     } 
 20.     if($maxheight && $height > $maxheight){ 
 21.       $heightratio = $maxheight/$height; 
 22.       $RESIZEHEIGHT=true; 
 23.     } 
 24.     if($RESIZEWIDTH && $RESIZEHEIGHT){ 
 25.       if($widthratio < $heightratio){ 
 26.         $ratio = $widthratio; 
 27.       }else{ 
 28.         $ratio = $heightratio; 
 29.       } 
 30.     }elseif($RESIZEWIDTH){ 
 31.       $ratio = $widthratio; 
 32.     }elseif($RESIZEHEIGHT){ 
 33.       $ratio = $heightratio; 
 34.     } 
 35.     $newwidth = $width * $ratio; 
 36.     $newheight = $height * $ratio; 
 37.     if(function_exists("imagecopyresampled")){ 
 38.        $newim = imagecreatetruecolor($newwidth, $newheight); 
 39.        imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
 40.     }else{ 
 41.       $newim = imagecreate($newwidth, $newheight); 
 42.        imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); 
 43.     } 
 44.     ImageJpeg ($newim,$name . ".jpg"); 
 45.     ImageDestroy ($newim); 
 46.   }else{ 
 47.     ImageJpeg ($im,$name . ".jpg"); 
 48.   } 
 49. } 
 50. 
 51. 
 52. if($_FILES['image']['size']){ 
 53.   if($_FILES['image']['type'] == "image/pjpeg"){ 
 54.     $im = imagecreatefromjpeg($_FILES['image']['tmp_name']); 
 55.   }elseif($_FILES['image']['type'] == "image/x-png"){ 
 56.     $im = imagecreatefrompng($_FILES['image']['tmp_name']); 
 57.   }elseif($_FILES['image']['type'] == "image/gif"){ 
 58.     $im = imagecreatefromgif($_FILES['image']['tmp_name']); 
 59.   } 
 60.   if($im){ 
 61.     if(file_exists("$FILENAME.jpg")){ 
 62.       unlink("$FILENAME.jpg"); 
 63.     } 
 64.     ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME); 
 65.     ImageDestroy ($im); 
 66.   } 
 67. } 
 68. 
 69. ?> 
 70. 
 71. <img src="<? echo($FILENAME.".jpg?reload=".rand(0,999999)); ?>"><br/><br/> 
 72. 
 73. <form enctype="multipart/form-data" method="post"> 
 74. <br/> 
 75. <input type="file" name="image" size="50" value="浏览"><p> 
 76. <input type="submit" value="上传图片"> 
 77. </form> 
 78. 
 79. </body> 
 80. </html> 

来源:PHP资讯    责编:豆豆技术应用

正在加载评论...