php gd库函数生成高清缩略图程序

gd库是php教程中一个处理图像的专用库,他可以方便快捷的处理大多数据处理,它提供了大量的图片处理函数,下面我们就利用gd库的函数来生成缩略图.

测试代码如下:

  1. <?php
  2. include('resizeimage.php');
  3. if(!emptyempty($_post)){
  4. echo($filename.".jpg?cache=".rand(0,999999));
  5. }
  6. ?>
  7. <form name="test" action="?submit=true" enctype="multipart/form-data" method="post" >
  8. <input type="file" name="image" size="50" value="浏览"><p>
  9. <input type="submit" value="上传图片">
  10. </form>

resizeimage.php 文件代码如下:

  1. <?php
  2. $filename="image.thumb";
  3. // 生成图片的宽度
  4. $resizewidth=400;
  5. // 生成图片的高度
  6. $resizeheight=400;
  7. function resizeimage($im,$maxwidth,$maxheight,$name){
  8. $width = imagesx($im);
  9. $height = imagesy($im);
  10. if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
  11. if($maxwidth && $width > $maxwidth){
  12. $widthratio = $maxwidth/$width;
  13. $resizewidth=true;
  14. }
  15. if($maxheight && $height > $maxheight){
  16. $heightratio = $maxheight/$height;
  17. $resizeheight=true;
  18. }
  19. if($resizewidth && $resizeheight){
  20. if($widthratio < $heightratio){
  21. $ratio = $widthratio;
  22. }else{
  23. $ratio = $heightratio;
  24. }
  25. }elseif($resizewidth){
  26. $ratio = $widthratio;
  27. }elseif($resizeheight){
  28. $ratio = $heightratio;
  29. }
  30. $newwidth = $width * $ratio;
  31. $newheight = $height * $ratio;
  32. if(function_exists("imagecopyresampled")){
  33. $newim = imagecreatetruecolor($newwidth, $newheight);
  34. imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  35. }else{
  36. $newim = imagecreate($newwidth, $newheight);
  37. imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  38. }
  39. imagejpeg ($newim,$name . ".jpg");
  40. imagedestroy ($newim);
  41. }else{
  42. imagejpeg ($im,$name . ".jpg");
  43. }
  44. }
  45. if($_files['image']['size']){
  46. if($_files['image']['type'] == "image/pjpeg"){
  47. $im = imagecreatefromjpeg($_files['image']['tmp_name']);
  48. }elseif($_files['image']['type'] == "image/x-png"){
  49. $im = imagecreatefrompng($_files['image']['tmp_name']);
  50. }elseif($_files['image']['type'] == "image/gif"){
  51. $im = imagecreatefromgif($_files['image']['tmp_name']);
  52. }
  53. if($im){
  54. if(file_exists("$filename.jpg")){
  55. unlink("$filename.jpg");
  56. }
  57. resizeimage($im,$resizewidth,$resizeheight,$filename);
  58. imagedestroy ($im);
  59. }
  60. } //开源代码phpfensi.com
  61. ?>