php简单实用生成缩略图代码

本程序是根据用户上传图片后再把上传的图片按比例生成缩略图,程序实例代码如下:

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