当前位置:Gxlcms > PHP教程 > phpGD库生成高质量缩略图(示例)

phpGD库生成高质量缩略图(示例)

时间:2021-07-01 10:21:17 帮助过:3人阅读

  1. $FILENAME="image.thumb";

  2. // 生成图片的宽度
  3. $RESIZEWIDTH=400;
  4. // 生成图片的高度
  5. $RESIZEHEIGHT=400;

  6. function ResizeImage($im,$maxwidth,$maxheight,$name){

  7. $width = imagesx($im);
  8. $height = imagesy($im);
  9. if(($maxwidth && $width > $maxwidth) || ($maxheight && $height > $maxheight)){
  10. if($maxwidth && $width > $maxwidth){
  11. $widthratio = $maxwidth/$width;
  12. $RESIZEWIDTH=true;
  13. }
  14. if($maxheight && $height > $maxheight){
  15. $heightratio = $maxheight/$height;
  16. $RESIZEHEIGHT=true;
  17. }
  18. if($RESIZEWIDTH && $RESIZEHEIGHT){
  19. if($widthratio < $heightratio){
  20. $ratio = $widthratio;
  21. }else{
  22. $ratio = $heightratio;
  23. }
  24. }elseif($RESIZEWIDTH){
  25. $ratio = $widthratio;
  26. }elseif($RESIZEHEIGHT){
  27. $ratio = $heightratio;
  28. }
  29. $newwidth = $width * $ratio;
  30. $newheight = $height * $ratio;
  31. if(function_exists("imagecopyresampled")){
  32. $newim = imagecreatetruecolor($newwidth, $newheight);
  33. imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  34. }else{
  35. $newim = imagecreate($newwidth, $newheight);
  36. imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  37. }
  38. ImageJpeg ($newim,$name . ".jpg");
  39. ImageDestroy ($newim);
  40. }else{
  41. ImageJpeg ($im,$name . ".jpg");
  42. }
  43. }

  44. if($_FILES['image']['size']){

  45. if($_FILES['image']['type'] == "image/pjpeg"){
  46. $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
  47. }elseif($_FILES['image']['type'] == "image/x-png"){
  48. $im = imagecreatefrompng($_FILES['image']['tmp_name']);
  49. }elseif($_FILES['image']['type'] == "image/gif"){
  50. $im = imagecreatefromgif($_FILES['image']['tmp_name']);
  51. }
  52. if($im){
  53. if(file_exists("$FILENAME.jpg")){
  54. unlink("$FILENAME.jpg");
  55. }
  56. ResizeImage($im,$RESIZEWIDTH,$RESIZEHEIGHT,$FILENAME);
  57. ImageDestroy ($im);
  58. }
  59. }
  60. ?>

2,测试代码(demo.php)

  1. /**
  2. * PHP生成高质量缩略图
  3. * by bbs.it-home.org
  4. */
  5. include('ResizeImage.php');
  6. if(!empty($_POST)){
  7. echo($FILENAME.".jpg?cache=".rand(0,999999));
  8. }
  9. ?>

人气教程排行