php生成缩略图代码

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