首页 > 语言 > PHP > 正文

php生成缩略图代码

2024-09-04 11:44:26
字体:大 中 小
来源:转载
供稿:网友
  1. <?php 
  2. # Constants 
  3. define("IMAGE_BASE", './'); 
  4. define("MAX_WIDTH", 150); 
  5. define("MAX_HEIGHT", 150); 
  6.  
  7. # Get image locationstr_replace('..', '', $_SERVER['QUERY_STRING']); 
  8. $image_file = 't.jpg'; 
  9. $image_path = IMAGE_BASE . "$image_file"; 
  10.  
  11. # Load image 
  12. $img = null; 
  13. $ext = strtolower(end(explode('.', $image_path))); 
  14. if ($ext == 'jpg' || $ext == 'jpeg') { 
  15.      $img = imagecreatefromjpeg($image_path); 
  16. } else if ($ext == 'png') { 
  17.      $img = @imagecreatefrompng($image_path); 
  18. # Only if your version of GD includes GIF support 
  19. } else if ($ext == 'gif') { 
  20.      $img = @imagecreatefrompng($image_path); 
  21. } 
  22.  
  23. # If an image was successfully loaded, test the image for size 
  24. if ($img) { 
  25.  
  26.      # Get image size and scale ratio 
  27.      $width = imagesx($img); 
  28.      $height = imagesy($img); 
  29.      $scale = min(MAX_WIDTH/$width, MAX_HEIGHT/$height); 
  30.  
  31.      # If the image is larger than the max shrink it 
  32.      if ($scale < 1) { 
  33.          $new_width =150; //floor($scale*$width); 
  34.          $new_height =150;// floor($scale*$height); 
  35.  
  36.          # Create a new temporary image 
  37.          $tmp_img = imagecreatetruecolor($new_width, $new_height); 
  38.  
  39.          # Copy and resize old image into new image 
  40.          imagecopyresized($tmp_img, $img, 0, 0, 0, 0,$new_width, $new_height, $width, $height); 
  41.          imagedestroy($img); 
  42.          $img = $tmp_img; 
  43.      } 
  44. } 
  45.  
  46. # Create error image if necessary 
  47. if (!$img) { 
  48.      $img = imagecreate(MAX_WIDTH, MAX_HEIGHT); 
  49.      imagecolorallocate($img,0,0,0); 
  50.      $c = imagecolorallocate($img,70,70,70 ); 
  51.      imageline($img,0,0,MAX_WIDTH,MAX_HEIGHT,$c2); 
  52.      imageline($img,MAX_WIDTH,0,0,MAX_HEIGHT,$c2); 
  53. }//开源代码Vevb.com 
  54.  
  55. # Display the image 
  56. header("Content-type: image/jpeg"); 
  57. imagejpeg($img); 
  58. imagedestroy($img); 
  59. ?> 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表