当前位置: 无忧屋首页 > 文章中心 > PHP >

php实现按照指定的尺寸像素压缩到指定路径图片源码

来源:网络

发布人:天道酬勤

发布时间:2024-11-14

php实现按照指定的尺寸像素压缩到指定路径图片源码

  1. /**     
  2.      * * 按照指定的尺寸压缩图片     
  3.      * * @param $source_path  原图路径
  4.      * * @param $imgWidth     目标宽度
  5.      * * @param $imgHeight    目标高度
  6.      * * @return bool|string     
  7.     */   
  8.     function resize_image($source_path, $imgWidth, $imgHeight)
  9.     {        
  10.         $source_info = getimagesize($source_path);        
  11.         $source_mime = $source_info['mime'];        
  12.         switch ($source_mime) {            
  13.             case 'image/gif':
  14.                 $source_image = imagecreatefromgif($source_path);               
  15.                 break;
  16.             case 'image/jpeg':
  17.                 $source_image = imagecreatefromjpeg($source_path);               
  18.                 break;
  19.             case 'image/png':
  20.                 $source_image = imagecreatefrompng($source_path);               
  21.                 break;
  22.             default:
  23.                 return false;
  24.                 break;        
  25.         }
  26.         $target_image  = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图
  27.         imagecopyresampled($target_image, $source_image, 0, 0, 0, 0, $imgWidth, $imgHeight, $source_info[0], $source_info[1]);
  28.         if(!imagejpeg($target_image, $source_path)){
  29.             $source_path = '';
  30.         }
  31.         imagedestroy($target_image);
  32.         return $source_path;
  33.     }

免责声明:文中图文均系网友发布,转载来自网络,如有侵权请联系右侧客服QQ删除,无忧屋网友发布此文仅为传递信息,不代表无忧屋平台认同其观点。