php实现图片按比例截取的方法

  1. filename ='img/test.jpg'
  2. $all_type=array(
  3. "jpg" =>array("create"=>"ImageCreateFromjpeg","output"=>"imagejpeg" ,"exn"=>".jpg"),
  4. "gif" =>array("create"=>"ImageCreateFromGIF","output"=>"imagegif" ,"exn"=>".gif"),
  5. "jpeg" =>array("create"=>"ImageCreateFromjpeg","output"=>"imagejpeg" ,"exn"=>".jpg"),
  6. "png" =>array("create"=>"imagecreatefrompng","output"=>"imagepng" ,"exn"=>".png"),
  7. "wbmp" =>array("create"=>"imagecreatefromwbmp","output"=>"image2wbmp","exn"=>".wbmp")
  8. );
  9. $imgtype=getimagesize($filename);
  10. $width=$imgtype[0];
  11. $height=$imgtype[1];
  12. $type=str_replace('image/','',$imgtype['mime']);
  13. $func_create=$all_type[$type]['create'];
  14. $func_output=$all_type[$type]['output'];
  15. $x=$y=0;
  16. if(($width* 100)>($height* 120))
  17. {
  18. $newwidth=ceil($height* 120/100);
  19. $newheight=$height;
  20. $x= ($width-$newwidth)/2;
  21. }
  22. elseif(($width* 100)<($height* 120))
  23. {
  24. $newheight=ceil($width* 100/120);
  25. $newwidth=$width;
  26. $y= ($height-$newheight)/2;
  27. }
  28. else
  29. {
  30. $newheight=$height;
  31. $newwidth=$width;
  32. }
  33. // Load
  34. $thumb= imagecreatetruecolor($newwidth,$newheight);
  35. $source=$func_create($filename);
  36. // Resize
  37. imagecopyresized($thumb,$source, 0, 0, 0, 0,$newwidth,$newheight,$newwidth,$newheight);
  38. // Output
  39. $func_output($thumb,'a.jpeg');