当前位置:Gxlcms > PHP教程 > 将图片保存为不同规格的图片的php代码

将图片保存为不同规格的图片的php代码

时间:2021-07-01 10:21:17 帮助过:23人阅读

  1. /**

  2. 图片处理类
  3. */
  4. class imagecls
  5. {
  6. /**
  7. * 文件信息
  8. */
  9. var $file = array();
  10. /**
  11. * 保存目录
  12. */
  13. var $dir = '';
  14. /**
  15. * 错误代码
  16. */
  17. var $error_code = 0;
  18. /**
  19. * 文件上传最大KB
  20. */
  21. var $max_size = -1;

  22. function es_imagecls()

  23. {

  24. }

  25. private function checkSize($size)
  26. {
  27. return !($size > $this->max_size) || (-1 == $this->max_size);
  28. }
  29. /**
  30. * 处理上传文件
  31. * @param array $file 上传的文件
  32. * @param string $dir 保存的目录
  33. * @return bool
  34. */
  35. function init($file, $dir = 'temp')
  36. {
  37. if(!is_array($file) || empty($file) || !$this->isUploadFile($file['tmp_name']) || trim($file['name']) == '' || $file['size'] == 0)
  38. {
  39. $this->file = array();
  40. $this->error_code = -1;
  41. return false;
  42. }
  43. else
  44. {
  45. $file['size'] = intval($file['size']);
  46. $file['name'] = trim($file['name']);
  47. $file['thumb'] = '';
  48. $file['ext'] = $this->fileExt($file['name']);
  49. $file['name'] = htmlspecialchars($file['name'], ENT_QUOTES);
  50. $file['is_image'] = $this->isImageExt($file['ext']);
  51. $file['file_dir'] = $this->getTargetDir($dir);
  52. $file['prefix'] = md5(microtime(true)).rand(10,99);
  53. $file['target'] = "./public/".$file['file_dir'].'/'.$file['prefix'].'.jpg'; //相对
  54. $file['local_target'] = APP_ROOT_PATH."public/".$file['file_dir'].'/'.$file['prefix'].'.jpg';//物理
  55. $this->file = &$file;
  56. $this->error_code = 0;
  57. return true;
  58. }
  59. }

  60. /**

  61. * 保存文件
  62. * @return bool
  63. */
  64. function save()
  65. {
  66. if(empty($this->file) || empty($this->file['tmp_name']))
  67. $this->error_code = -101;
  68. elseif(!$this->checkSize($this->file['size']))
  69. $this->error_code = -105;
  70. elseif(!$this->file['is_image'])
  71. $this->error_code = -102;
  72. elseif(!$this->saveFile($this->file['tmp_name'], $this->file['local_target']))
  73. $this->error_code = -103;
  74. elseif($this->file['is_image'] &&
  75. (!$this->file['image_info'] = $this->getImageInfo($this->file['local_target'], true)))
  76. {
  77. $this->error_code = -104;
  78. @unlink($this->file['local_target']);
  79. }
  80. else
  81. {
  82. $this->error_code = 0;
  83. return true;
  84. }
  85. return false;
  86. }

  87. /**

  88. * 获取错误代码
  89. * @return number
  90. */
  91. function error()
  92. {
  93. return $this->error_code;
  94. }

  95. /**

  96. * 获取文件扩展名
  97. * @return string
  98. */
  99. function fileExt($file_name)
  100. {
  101. return addslashes(strtolower(substr(strrchr($file_name, '.'), 1, 10)));
  102. }

  103. /**

  104. * 根据扩展名判断文件是否为图像
  105. * @param string $ext 扩展名
  106. * @return bool
  107. */
  108. function isImageExt($ext)
  109. {
  110. static $img_ext = array('jpg', 'jpeg', 'png', 'bmp','gif','giff');
  111. return in_array($ext, $img_ext) ? 1 : 0;
  112. }

  113. /**

  114. * 获取图像信息
  115. * @param string $target 文件路径
  116. * @return mixed
  117. */
  118. function getImageInfo($target)
  119. {
  120. $ext = es_imagecls::fileExt($target);
  121. $is_image = es_imagecls::isImageExt($ext);

  122. if(!$is_image)

  123. return false;
  124. elseif(!is_readable($target))
  125. return false;
  126. elseif($image_info = @getimagesize($target))
  127. {
  128. list($width, $height, $type) = !empty($image_info) ? $image_info :
  129. array('', '', '');
  130. $size = $width * $height;
  131. if($is_image && !in_array($type, array(1,2,3,6,13)))
  132. return false;

  133. $image_info['type'] =

  134. strtolower (substr(image_type_to_extension($image_info[2]),1));
  135. return $image_info;
  136. }
  137. else
  138. return false;
  139. }

  140. /**

  141. * 获取是否充许上传文件
  142. * @param string $source 文件路径
  143. * @return bool
  144. */
  145. function isUploadFile($source)
  146. {
  147. return $source && ($source != 'none') &&
  148. (is_uploaded_file($source) || is_uploaded_file(str_replace('\\', '\', $source)));
  149. }

  150. /**

  151. * 获取保存的路径
  152. * @param string $dir 指定的保存目录
  153. * @return string
  154. */
  155. function getTargetDir($dir)
  156. {
  157. if (!is_dir(APP_ROOT_PATH."public/".$dir)) {
  158. @mkdir(APP_ROOT_PATH."public/".$dir);
  159. @chmod(APP_ROOT_PATH."public/".$dir, 0777);
  160. }
  161. return $dir;
  162. }

  163. /**

  164. * 保存文件
  165. * @param string $source 源文件路径
  166. * @param string $target 目录文件路径
  167. * @return bool
  168. */
  169. private function saveFile($source, $target)
  170. {
  171. if(!es_imagecls::isUploadFile($source))
  172. $succeed = false;
  173. elseif(@copy($source, $target))
  174. $succeed = true;
  175. elseif(function_exists('move_uploaded_file') &&
  176. @move_uploaded_file($source, $target))
  177. $succeed = true;
  178. elseif (@is_readable($source) &&
  179. (@$fp_s = fopen($source, 'rb')) && (@$fp_t = fopen($target, 'wb')))
  180. {
  181. while (!feof($fp_s))
  182. {
  183. $s = @fread($fp_s, 1024 * 512);
  184. @fwrite($fp_t, $s);
  185. }
  186. fclose($fp_s);
  187. fclose($fp_t);
  188. $succeed = true;
  189. }

  190. if($succeed)

  191. {
  192. $this->error_code = 0;
  193. @chmod($target, 0644);
  194. @unlink($source);
  195. }
  196. else
  197. {
  198. $this->error_code = 0;
  199. }

  200. return $succeed;

  201. }

  202. public function thumb($image,$maxWidth=200,$maxHeight=50,$gen = 0,

  203. $interlace=true,$filepath = '',$is_preview = true)
  204. {
  205. $info = es_imagecls::getImageInfo($image);

  206. if($info !== false)

  207. {
  208. $srcWidth = $info[0];
  209. $srcHeight = $info[1];
  210. $type = $info['type'];

  211. $interlace = $interlace? 1:0;

  212. unset($info);

  213. if($maxWidth > 0 && $maxHeight > 0)

  214. $scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight);
  215. // 计算缩放比例
  216. elseif($maxWidth == 0)
  217. $scale = $maxHeight/$srcHeight;
  218. elseif($maxHeight == 0)
  219. $scale = $maxWidth/$srcWidth;

  220. $paths = pathinfo($image);
  221. $paths['filename'] = trim(strtolower($paths['basename']),
  222. ".".strtolower($paths['extension']));
  223. $basefilename = explode("_",$paths['filename']);
  224. $basefilename = $basefilename[0];
  225. if(empty($filepath))
  226. {
  227. if($is_preview)
  228. $thumbname = $paths['dirname'].'/'.$basefilename.
  229. '_'.$maxWidth.'x'.$maxHeight.'.jpg';
  230. else
  231. $thumbname = $paths['dirname'].'/'.$basefilename.
  232. 'o_'.$maxWidth.'x'.$maxHeight.'.jpg';
  233. }
  234. else
  235. $thumbname = $filepath;

  236. $thumburl = str_replace(APP_ROOT_PATH,'./',$thumbname);

  237. if($scale >= 1)
  238. {
  239. // 超过原图大小不再缩略
  240. $width = $srcWidth;
  241. $height = $srcHeight;
  242. if(!$is_preview)
  243. {
  244. //非预览模式写入原图
  245. file_put_contents($thumbname,file_get_contents($image)); //用原图写入
  246. return array('url'=>$thumburl,'path'=>$thumbname);
  247. }
  248. }
  249. else
  250. {
  251. // 缩略图尺寸
  252. $width = (int)($srcWidth*$scale);
  253. $height = (int)($srcHeight*$scale);
  254. }
  255. if($gen == 1)
  256. {
  257. $width = $maxWidth;
  258. $height = $maxHeight;
  259. }

  260. // 载入原图

  261. $createFun = 'imagecreatefrom'.($type=='jpg'?'jpeg':$type);
  262. if(!function_exists($createFun))
  263. $createFun = 'imagecreatefromjpeg';

  264. $srcImg = $createFun($image);

  265. //创建缩略图

  266. if($type!='gif' && function_exists('imagecreatetruecolor'))
  267. $thumbImg = imagecreatetruecolor($width, $height);
  268. else
  269. $thumbImg = imagecreate($width, $height);

  270. $x = 0;

  271. $y = 0;

  272. if($gen == 1 && $maxWidth > 0 && $maxHeight > 0)

  273. {
  274. $resize_ratio = $maxWidth/$maxHeight;
  275. $src_ratio = $srcWidth/$srcHeight;
  276. if($src_ratio >= $resize_ratio)
  277. {
  278. $x = ($srcWidth - ($resize_ratio * $srcHeight)) / 2;
  279. $width = ($height * $srcWidth) / $srcHeight;
  280. }
  281. else
  282. {
  283. $y = ($srcHeight - ( (1 / $resize_ratio) * $srcWidth)) / 2;
  284. $height = ($width * $srcHeight) / $srcWidth;
  285. }
  286. }

  287. // 复制图片

  288. if(function_exists("imagecopyresampled"))
  289. imagecopyresampled($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height,
  290. $srcWidth,$srcHeight);
  291. else
  292. imagecopyresized($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height,
  293. $srcWidth,$srcHeight);
  294. if('gif'==$type || 'png'==$type) {
  295. $background_color = imagecolorallocate($thumbImg, 0,255,0); // 指派一个绿色
  296. imagecolortransparent($thumbImg,$background_color);
  297. // 设置为透明色,若注释掉该行则输出绿色的图
  298. }

  299. // 对jpeg图形设置隔行扫描

  300. if('jpg'==$type || 'jpeg'==$type)
  301. imageinterlace($thumbImg,$interlace);

  302. // 生成图片

  303. imagejpeg($thumbImg,$thumbname,100);
  304. imagedestroy($thumbImg);
  305. imagedestroy($srcImg);

  306. return array('url'=>$thumburl,'path'=>$thumbname);

  307. }
  308. return false;
  309. }

  310. public function make_thumb($srcImg,$srcWidth,$srcHeight,$type,$maxWidth=200,

  311. $maxHeight=50,$gen = 0)
  312. {

  313. $interlace = $interlace? 1:0;

  314. if($maxWidth > 0 && $maxHeight > 0)

  315. $scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight);
  316. // 计算缩放比例
  317. elseif($maxWidth == 0)
  318. $scale = $maxHeight/$srcHeight;
  319. elseif($maxHeight == 0)
  320. $scale = $maxWidth/$srcWidth;

  321. if($scale >= 1)

  322. {
  323. // 超过原图大小不再缩略
  324. $width = $srcWidth;
  325. $height = $srcHeight;
  326. }
  327. else
  328. {
  329. // 缩略图尺寸
  330. $width = (int)($srcWidth*$scale);
  331. $height = (int)($srcHeight*$scale);
  332. }

  333. if($gen == 1)

  334. {
  335. $width = $maxWidth;
  336. $height = $maxHeight;
  337. }

  338. //创建缩略图
  339. if($type!='gif' && function_exists('imagecreatetruecolor'))
  340. $thumbImg = imagecreatetruecolor($width, $height);
  341. else
  342. $thumbImg = imagecreatetruecolor($width, $height);

  343. $x = 0;

  344. $y = 0;

  345. if($gen == 1 && $maxWidth > 0 && $maxHeight > 0)

  346. {
  347. $resize_ratio = $maxWidth/$maxHeight;
  348. $src_ratio = $srcWidth/$srcHeight;
  349. if($src_ratio >= $resize_ratio)
  350. {
  351. $x = ($srcWidth - ($resize_ratio * $srcHeight)) / 2;
  352. $width = ($height * $srcWidth) / $srcHeight;
  353. }
  354. else
  355. {
  356. $y = ($srcHeight - ( (1 / $resize_ratio) * $srcWidth)) / 2;
  357. $height = ($width * $srcHeight) / $srcWidth;
  358. }
  359. }

  360. // 复制图片

  361. if(function_exists("imagecopyresampled"))
  362. imagecopyresampled($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height,
  363. $srcWidth,$srcHeight);
  364. else
  365. imagecopyresized($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height,
  366. $srcWidth,$srcHeight);
  367. if('gif'==$type || 'png'==$type) {
  368. $background_color = imagecolorallocate($thumbImg, 255,255,255);
  369. // 指派一个绿色
  370. imagecolortransparent($thumbImg,$background_color);
  371. // 设置为透明色,若注释掉该行则输出绿色的图
  372. }

  373. // 对jpeg图形设置隔行扫描

  374. if('jpg'==$type || 'jpeg'==$type)
  375. imageinterlace($thumbImg,$interlace);

  376. return $thumbImg;

  377. }

  378. public function water($source,$water,$alpha=80,$position="0")
  379. {
  380. //检查文件是否存在
  381. if(!file_exists($source)||!file_exists($water))
  382. return false;

  383. //图片信息

  384. $sInfo = es_imagecls::getImageInfo($source);
  385. $wInfo = es_imagecls::getImageInfo($water);

  386. //如果图片小于水印图片,不生成图片

  387. if($sInfo["0"] < $wInfo["0"] || $sInfo['1'] < $wInfo['1'])
  388. return false;

  389. if(is_animated_gif($source))
  390. {
  391. require_once APP_ROOT_PATH."system/utils/gif_encoder.php";
  392. require_once APP_ROOT_PATH."system/utils/gif_reader.php";

  393. $gif = new GIFReader();

  394. $gif->load($source);
  395. foreach($gif->IMGS['frames'] as $k=>$img)
  396. {
  397. $im = imagecreatefromstring($gif->getgif($k));
  398. //为im加水印
  399. $sImage=$im;
  400. $wCreateFun="imagecreatefrom".$wInfo['type'];
  401. if(!function_exists($wCreateFun))
  402. $wCreateFun = 'imagecreatefromjpeg';
  403. $wImage=$wCreateFun($water);
  404. //设定图像的混色模式
  405. imagealphablending($wImage, true);
  406. switch (intval($position))
  407. {
  408. case 0: break;
  409. //左上
  410. case 1:
  411. $posY=0;
  412. $posX=0;
  413. //生成混合图像
  414. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  415. break;
  416. //右上
  417. case 2:
  418. $posY=0;
  419. $posX=$sInfo[0]-$wInfo[0];
  420. //生成混合图像
  421. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  422. break;
  423. //左下
  424. case 3:
  425. $posY=$sInfo[1]-$wInfo[1];
  426. $posX=0;
  427. //生成混合图像
  428. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  429. break;
  430. //右下
  431. case 4:
  432. $posY=$sInfo[1]-$wInfo[1];
  433. $posX=$sInfo[0]-$wInfo[0];
  434. //生成混合图像
  435. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  436. break;
  437. //居中
  438. case 5:
  439. $posY=$sInfo[1]/2-$wInfo[1]/2;
  440. $posX=$sInfo[0]/2-$wInfo[0]/2;
  441. //生成混合图像
  442. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  443. break;
  444. }
  445. //end im加水印
  446. ob_start();
  447. imagegif($sImage);
  448. $content = ob_get_contents();
  449. ob_end_clean();
  450. $frames [ ] = $content;
  451. $framed [ ] = $img['frameDelay'];
  452. }
  453. $gif_maker = new GIFEncoder (
  454. $frames,
  455. $framed,
  456. 0,
  457. 2,
  458. 0, 0, 0,
  459. "bin" //bin为二进制 url为地址
  460. );
  461. $image_rs = $gif_maker->GetAnimation ( );
  462. //如果没有给出保存文件名,默认为原图像名
  463. @unlink($source);
  464. //保存图像
  465. file_put_contents($source,$image_rs);
  466. return true;
  467. }
  468. //建立图像
  469. $sCreateFun="imagecreatefrom".$sInfo['type'];
  470. if(!function_exists($sCreateFun))
  471. $sCreateFun = 'imagecreatefromjpeg';
  472. $sImage=$sCreateFun($source);

  473. $wCreateFun="imagecreatefrom".$wInfo['type'];

  474. if(!function_exists($wCreateFun))
  475. $wCreateFun = 'imagecreatefromjpeg';
  476. $wImage=$wCreateFun($water);

  477. //设定图像的混色模式

  478. imagealphablending($wImage, true);

  479. switch (intval($position))

  480. {
  481. case 0: break;
  482. //左上
  483. case 1:
  484. $posY=0;
  485. $posX=0;
  486. //生成混合图像
  487. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  488. break;
  489. //右上
  490. case 2:
  491. $posY=0;
  492. $posX=$sInfo[0]-$wInfo[0];
  493. //生成混合图像
  494. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  495. break;
  496. //左下
  497. case 3:
  498. $posY=$sInfo[1]-$wInfo[1];
  499. $posX=0;
  500. //生成混合图像
  501. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  502. break;
  503. //右下
  504. case 4:
  505. $posY=$sInfo[1]-$wInfo[1];
  506. $posX=$sInfo[0]-$wInfo[0];
  507. //生成混合图像
  508. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  509. break;
  510. //居中
  511. case 5:
  512. $posY=$sInfo[1]/2-$wInfo[1]/2;
  513. $posX=$sInfo[0]/2-$wInfo[0]/2;
  514. //生成混合图像
  515. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  516. break;
  517. }

  518. //如果没有给出保存文件名,默认为原图像名

  519. @unlink($source);
  520. //保存图像
  521. imagejpeg($sImage,$source,100);
  522. imagedestroy($sImage);
  523. }
  524. }

  525. if(!function_exists('image_type_to_extension'))

  526. {
  527. function image_type_to_extension($imagetype)
  528. {
  529. if(empty($imagetype))
  530. return false;

  531. switch($imagetype)

  532. {
  533. case IMAGETYPE_GIF : return '.gif';
  534. case IMAGETYPE_JPEG : return '.jpeg';
  535. case IMAGETYPE_PNG : return '.png';
  536. case IMAGETYPE_SWF : return '.swf';
  537. case IMAGETYPE_PSD : return '.psd';
  538. case IMAGETYPE_BMP : return '.bmp';
  539. case IMAGETYPE_TIFF_II : return '.tiff';
  540. case IMAGETYPE_TIFF_MM : return '.tiff';
  541. case IMAGETYPE_JPC : return '.jpc';
  542. case IMAGETYPE_JP2 : return '.jp2';
  543. case IMAGETYPE_JPX : return '.jpf';
  544. case IMAGETYPE_JB2 : return '.jb2';
  545. case IMAGETYPE_SWC : return '.swc';
  546. case IMAGETYPE_IFF : return '.aiff';
  547. case IMAGETYPE_WBMP : return '.wbmp';
  548. case IMAGETYPE_XBM : return '.xbm';
  549. default : return false;
  550. }
  551. }
  552. }
  553. ?>

2.get_spec_img()调用图片类,然后再用下面的方法保存不同规格的图片并返回图片连接

  1. //获取相应规格的图片地址
  2. //gen=0:保持比例缩放,不剪裁,如高为0,则保证宽度按比例缩放 gen=1:保证长宽,剪裁
  3. function get_spec_image($img_path,$width=0,$height=0,$gen=0,$is_preview=true)
  4. {
  5. if($width==0)
  6. $new_path = $img_path;
  7. else
  8. {
  9. $img_name = substr($img_path,0,-4);
  10. $img_ext = substr($img_path,-3);
  11. if($is_preview)
  12. $new_path = $img_name."_".$width."x".$height.".jpg";
  13. else
  14. $new_path = $img_name."o_".$width."x".$height.".jpg";
  15. if(!file_exists($new_path))
  16. {
  17. require_once "imagecls.php";
  18. $imagec = new imagecls();
  19. $thumb = $imagec->thumb($img_path,$width,$height,$gen,true,"
  20. ",$is_preview);
  21. if(app_conf("PUBLIC_DOMAIN_ROOT")!='')
  22. {
  23. $paths = pathinfo($new_path);
  24. $path = str_replace("./","",$paths['dirname']);
  25. $filename = $paths['basename'];
  26. $pathwithoupublic = str_replace("public/","",$path);
  27. $file_data = @file_get_contents($path.$file);
  28.     $img = @imagecreatefromstring($file_data);
  29.     if($img!==false)
  30.     {
  31.       $save_path = "public/".$path;
  32.       if(!is_dir($save_path))
  33.       {
  34.         @mk_dir($save_path);     
  35.       }
  36.       @file_put_contents($save_path.$name,$file_data);
  37.     }
  38. }
  39. }
  40. }
  41. return $new_path;
  42. }

3.使用方法:

  1. //im:将店铺图片保存为3种规格:小图:48x48,中图120x120,大图200x200
  2. $small_url=get_spec_image($data['image'],48,48,0);
  3. $
  4. middle_url=get_spec_image($data['image'],120,120,0);
  5. $big_url=get_spec_image($data['image'],200,200,0);

人气教程排行