php将图片保存为不同尺寸图片的图片类实例

这篇文章主要介绍了php将图片保存为不同尺寸图片的图片类,涉及php图片操作的保存、复制、缩略图等常用技巧,并封装成一个类文件以便于调用,非常具有实用价值,需要的朋友可以参考下。

本文实例讲述了php将图片保存为不同规格的图片类,分享给大家供大家参考,具体如下:

图片处理类.imagecls.php如下:

  1. <?php
  2. /**
  3. 图片处理类
  4. */
  5. class imagecls
  6. {
  7. /**
  8. * 文件信息
  9. */
  10. var $file = array();
  11. /**
  12. * 保存目录
  13. */
  14. var $dir = '';
  15. /**
  16. * 错误代码
  17. */
  18. var $error_code = 0;
  19. /**
  20. * 文件上传最大KB
  21. */
  22. var $max_size = -1;
  23. function es_imagecls()
  24. {
  25. }
  26. private function checkSize($size)
  27. {
  28. return !($size > $this->max_size) || (-1 == $this->max_size);
  29. }
  30. /**
  31. * 处理上传文件
  32. * @param array $file 上传的文件
  33. * @param string $dir 保存的目录
  34. * @return bool
  35. */
  36. function init($file, $dir = 'temp')
  37. {
  38. if(!is_array($file) || emptyempty($file) || !$this->isUploadFile($file['tmp_name']) || trim($file['name']) == '' || $file['size'] == 0)
  39. {
  40. $this->file = array();
  41. $this->error_code = -1;
  42. return false;
  43. }
  44. else
  45. {
  46. $file['size'] = intval($file['size']);
  47. $file['name'] = trim($file['name']);
  48. $file['thumb'] = '';
  49. $file['ext'] = $this->fileExt($file['name']);
  50. $file['name'] = htmlspecialchars($file['name'], ENT_QUOTES);
  51. $file['is_image'] = $this->isImageExt($file['ext']);
  52. $file['file_dir'] = $this->getTargetDir($dir);
  53. $file['prefix'] = md5(microtime(true)).rand(10,99);
  54. $file['target'] = "./public/".$file['file_dir'].'/'.$file['prefix'].'.jpg'; //相对
  55. $file['local_target'] = APP_ROOT_PATH."public/".$file['file_dir'].'/'.$file['prefix'].'.jpg'; //物理
  56. $this->file = &$file;
  57. $this->error_code = 0;
  58. return true;
  59. }
  60. }
  61. /**
  62. * 保存文件
  63. * @return bool
  64. */
  65. function save()
  66. {
  67. if(emptyempty($this->file) || emptyempty($this->file['tmp_name']))
  68. $this->error_code = -101;
  69. elseif(!$this->checkSize($this->file['size']))
  70. $this->error_code = -105;
  71. elseif(!$this->file['is_image'])
  72. $this->error_code = -102;
  73. elseif(!$this->saveFile($this->file['tmp_name'], $this->file['local_target']))
  74. $this->error_code = -103;
  75. elseif($this->file['is_image'] && (!$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) = !emptyempty($image_info) ? $image_info : array('', '', '');
  129. $size = $width * $height;
  130. if($is_image && !in_array($type, array(1,2,3,6,13)))
  131. return false;
  132. $image_info['type'] = strtolower(substr(image_type_to_extension($image_info[2]),1));
  133. return $image_info;
  134. }
  135. else
  136. return false;
  137. }
  138. /**
  139. * 获取是否充许上传文件
  140. * @param string $source 文件路径
  141. * @return bool
  142. */
  143. function isUploadFile($source)
  144. {
  145. return $source && ($source != 'none') && (is_uploaded_file($source) || is_uploaded_file(str_replace('\\\\', '\\', $source)));
  146. }
  147. /**
  148. * 获取保存的路径
  149. * @param string $dir 指定的保存目录
  150. * @return string
  151. */
  152. function getTargetDir($dir)
  153. {
  154. if (!is_dir(APP_ROOT_PATH."public/".$dir)) {
  155. @mkdir(APP_ROOT_PATH."public/".$dir);
  156. @chmod(APP_ROOT_PATH."public/".$dir, 0777);
  157. }
  158. return $dir;
  159. }
  160. /**
  161. * 保存文件
  162. * @param string $source 源文件路径
  163. * @param string $target 目录文件路径
  164. * @return bool
  165. */
  166. private function saveFile($source, $target)
  167. {
  168. if(!es_imagecls::isUploadFile($source))
  169. $succeed = false;
  170. elseif(@copy($source, $target))
  171. $succeed = true;
  172. elseif(function_exists('move_uploaded_file') && @move_uploaded_file($source, $target))
  173. $succeed = true;
  174. elseif (@is_readable($source) && (@$fp_s = fopen($source, 'rb')) && (@$fp_t = fopen($target, 'wb')))
  175. {
  176. while (!feof($fp_s))
  177. {
  178. $s = @fread($fp_s, 1024 * 512);
  179. @fwrite($fp_t, $s);
  180. }
  181. fclose($fp_s);
  182. fclose($fp_t);
  183. $succeed = true;
  184. }
  185. if($succeed)
  186. {
  187. $this->error_code = 0;
  188. @chmod($target, 0644);
  189. @unlink($source);
  190. }
  191. else
  192. {
  193. $this->error_code = 0;
  194. }
  195. return $succeed;
  196. }
  197. public function thumb($image,$maxWidth=200,$maxHeight=50,$gen = 0,$interlace=true,$filepath = '',$is_preview = true)
  198. {
  199. $info = es_imagecls::getImageInfo($image);
  200. if($info !== false)
  201. {
  202. $srcWidth = $info[0];
  203. $srcHeight = $info[1];
  204. $type = $info['type'];
  205. $interlace = $interlace? 1:0;
  206. unset($info);
  207. if($maxWidth > 0 && $maxHeight > 0)
  208. $scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight); // 计算缩放比例
  209. elseif($maxWidth == 0)
  210. $scale = $maxHeight/$srcHeight;
  211. elseif($maxHeight == 0)
  212. $scale = $maxWidth/$srcWidth;
  213. $paths = pathinfo($image);
  214. $paths['filename'] = trim(strtolower($paths['basename']),".".strtolower($paths['extension']));
  215. $basefilename = explode("_",$paths['filename']);
  216. $basefilename = $basefilename[0];
  217. if(emptyempty($filepath))
  218. {
  219. if($is_preview)
  220. $thumbname = $paths['dirname'].'/'.$basefilename.'_'.$maxWidth.'x'.$maxHeight.'.jpg';
  221. else
  222. $thumbname = $paths['dirname'].'/'.$basefilename.'o_'.$maxWidth.'x'.$maxHeight.'.jpg';
  223. }
  224. else
  225. $thumbname = $filepath;
  226. $thumburl = str_replace(APP_ROOT_PATH,'./',$thumbname);
  227. if($scale >= 1)
  228. {
  229. // 超过原图大小不再缩略
  230. $width = $srcWidth;
  231. $height = $srcHeight;
  232. if(!$is_preview)
  233. {
  234. //非预览模式写入原图
  235. file_put_contents($thumbname,file_get_contents($image)); //用原图写入
  236. return array('url'=>$thumburl,'path'=>$thumbname);
  237. }
  238. }
  239. else
  240. {
  241. // 缩略图尺寸
  242. $width = (int)($srcWidth*$scale);
  243. $height = (int)($srcHeight*$scale);
  244. }
  245. if($gen == 1)
  246. {
  247. $width = $maxWidth;
  248. $height = $maxHeight;
  249. }
  250. // 载入原图
  251. $createFun = 'imagecreatefrom'.($type=='jpg'?'jpeg':$type);
  252. if(!function_exists($createFun))
  253. $createFun = 'imagecreatefromjpeg';
  254. $srcImg = $createFun($image);
  255. //创建缩略图
  256. if($type!='gif' && function_exists('imagecreatetruecolor'))
  257. $thumbImg = imagecreatetruecolor($width, $height);
  258. else
  259. $thumbImg = imagecreate($width, $height);
  260. $x = 0;
  261. $y = 0;
  262. if($gen == 1 && $maxWidth > 0 && $maxHeight > 0)
  263. {
  264. $resize_ratio = $maxWidth/$maxHeight;
  265. $src_ratio = $srcWidth/$srcHeight;
  266. if($src_ratio >= $resize_ratio)
  267. {
  268. $x = ($srcWidth - ($resize_ratio * $srcHeight)) / 2;
  269. $width = ($height * $srcWidth) / $srcHeight;
  270. }
  271. else
  272. {
  273. $y = ($srcHeight - ( (1 / $resize_ratio) * $srcWidth)) / 2;
  274. $height = ($width * $srcHeight) / $srcWidth;
  275. }
  276. }
  277. // 复制图片
  278. if(function_exists("imagecopyresampled"))
  279. imagecopyresampled($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height, $srcWidth,$srcHeight);
  280. else
  281. imagecopyresized($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height, $srcWidth,$srcHeight);
  282. if('gif'==$type || 'png'==$type) {
  283. $background_color = imagecolorallocate($thumbImg, 0,255,0); // 指派一个绿色
  284. imagecolortransparent($thumbImg,$background_color); // 设置为透明色,若注释掉该行则输出绿色的图
  285. }
  286. // 对jpeg图形设置隔行扫描
  287. if('jpg'==$type || 'jpeg'==$type)
  288. imageinterlace($thumbImg,$interlace);
  289. // 生成图片
  290. imagejpeg($thumbImg,$thumbname,100);
  291. imagedestroy($thumbImg);
  292. imagedestroy($srcImg);
  293. return array('url'=>$thumburl,'path'=>$thumbname);
  294. }
  295. return false;
  296. }
  297. public function make_thumb($srcImg,$srcWidth,$srcHeight,$type,$maxWidth=200,$maxHeight=50,$gen = 0)
  298. {
  299. $interlace = $interlace? 1:0;
  300. if($maxWidth > 0 && $maxHeight > 0)
  301. $scale = min($maxWidth/$srcWidth, $maxHeight/$srcHeight); // 计算缩放比例
  302. elseif($maxWidth == 0)
  303. $scale = $maxHeight/$srcHeight;
  304. elseif($maxHeight == 0)
  305. $scale = $maxWidth/$srcWidth;
  306. if($scale >= 1)
  307. {
  308. // 超过原图大小不再缩略
  309. $width = $srcWidth;
  310. $height = $srcHeight;
  311. }
  312. else
  313. {
  314. // 缩略图尺寸
  315. $width = (int)($srcWidth*$scale);
  316. $height = (int)($srcHeight*$scale);
  317. }
  318. if($gen == 1)
  319. {
  320. $width = $maxWidth;
  321. $height = $maxHeight;
  322. }
  323. //创建缩略图
  324. if($type!='gif' && function_exists('imagecreatetruecolor'))
  325. $thumbImg = imagecreatetruecolor($width, $height);
  326. else
  327. $thumbImg = imagecreatetruecolor($width, $height);
  328. $x = 0;
  329. $y = 0;
  330. if($gen == 1 && $maxWidth > 0 && $maxHeight > 0)
  331. {
  332. $resize_ratio = $maxWidth/$maxHeight;
  333. $src_ratio = $srcWidth/$srcHeight;
  334. if($src_ratio >= $resize_ratio)
  335. {
  336. $x = ($srcWidth - ($resize_ratio * $srcHeight)) / 2;
  337. $width = ($height * $srcWidth) / $srcHeight;
  338. }
  339. else
  340. {
  341. $y = ($srcHeight - ( (1 / $resize_ratio) * $srcWidth)) / 2;
  342. $height = ($width * $srcHeight) / $srcWidth;
  343. }
  344. }
  345. // 复制图片
  346. if(function_exists("imagecopyresampled"))
  347. imagecopyresampled($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height, $srcWidth,$srcHeight);
  348. else
  349. imagecopyresized($thumbImg, $srcImg, 0, 0, $x, $y, $width, $height, $srcWidth,$srcHeight);
  350. if('gif'==$type || 'png'==$type) {
  351. $background_color = imagecolorallocate($thumbImg, 255,255,255); // 指派一个绿色
  352. imagecolortransparent($thumbImg,$background_color); // 设置为透明色,若注释掉该行则输出绿色的图
  353. }
  354. // 对jpeg图形设置隔行扫描
  355. if('jpg'==$type || 'jpeg'==$type)
  356. imageinterlace($thumbImg,$interlace);
  357. return $thumbImg;
  358. }
  359. public function water($source,$water,$alpha=80,$position="0")
  360. {
  361. //检查文件是否存在
  362. if(!file_exists($source)||!file_exists($water))
  363. return false;
  364. //图片信息
  365. $sInfo = es_imagecls::getImageInfo($source);
  366. $wInfo = es_imagecls::getImageInfo($water);
  367. //如果图片小于水印图片,不生成图片
  368. if($sInfo["0"] < $wInfo["0"] || $sInfo['1'] < $wInfo['1'])
  369. return false;
  370. if(is_animated_gif($source))
  371. {
  372. require_once APP_ROOT_PATH."system/utils/gif_encoder.php";
  373. require_once APP_ROOT_PATH."system/utils/gif_reader.php";
  374. $gif = new GIFReader();
  375. $gif->load($source);
  376. foreach($gif->IMGS['frames'] as $k=>$img)
  377. {
  378. $im = imagecreatefromstring($gif->getgif($k));
  379. //为im加水印
  380. $sImage=$im;
  381. $wCreateFun="imagecreatefrom".$wInfo['type'];
  382. if(!function_exists($wCreateFun))
  383. $wCreateFun = 'imagecreatefromjpeg';
  384. $wImage=$wCreateFun($water);
  385. //设定图像的混色模式
  386. imagealphablending($wImage, true);
  387. switch (intval($position))
  388. {
  389. case 0: break;
  390. //左上
  391. case 1:
  392. $posY=0;
  393. $posX=0;
  394. //生成混合图像
  395. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  396. break;
  397. //右上
  398. case 2:
  399. $posY=0;
  400. $posX=$sInfo[0]-$wInfo[0];
  401. //生成混合图像
  402. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  403. break;
  404. //左下
  405. case 3:
  406. $posY=$sInfo[1]-$wInfo[1];
  407. $posX=0;
  408. //生成混合图像
  409. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  410. break;
  411. //右下
  412. case 4:
  413. $posY=$sInfo[1]-$wInfo[1];
  414. $posX=$sInfo[0]-$wInfo[0];
  415. //生成混合图像
  416. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  417. break;
  418. //居中
  419. case 5:
  420. $posY=$sInfo[1]/2-$wInfo[1]/2;
  421. $posX=$sInfo[0]/2-$wInfo[0]/2;
  422. //生成混合图像
  423. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  424. break;
  425. }
  426. //end im加水印
  427. ob_start();
  428. imagegif($sImage);
  429. $content = ob_get_contents();
  430. ob_end_clean();
  431. $frames [ ] = $content;
  432. $framed [ ] = $img['frameDelay'];
  433. }
  434. $gif_maker = new GIFEncoder (
  435. $frames,
  436. $framed,
  437. 0,
  438. 2,
  439. 0, 0, 0,
  440. "bin" //bin为二进制 url为地址
  441. );
  442. $image_rs = $gif_maker->GetAnimation ( );
  443. //如果没有给出保存文件名,默认为原图像名
  444. @unlink($source);
  445. //保存图像
  446. file_put_contents($source,$image_rs);
  447. return true;
  448. }
  449. //建立图像
  450. $sCreateFun="imagecreatefrom".$sInfo['type'];
  451. if(!function_exists($sCreateFun))
  452. $sCreateFun = 'imagecreatefromjpeg';
  453. $sImage=$sCreateFun($source);
  454. $wCreateFun="imagecreatefrom".$wInfo['type'];
  455. if(!function_exists($wCreateFun))
  456. $wCreateFun = 'imagecreatefromjpeg';
  457. $wImage=$wCreateFun($water);
  458. //设定图像的混色模式
  459. imagealphablending($wImage, true);
  460. switch (intval($position))
  461. {
  462. case 0: break;
  463. //左上
  464. case 1:
  465. $posY=0;
  466. $posX=0;
  467. //生成混合图像
  468. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  469. break;
  470. //右上
  471. case 2:
  472. $posY=0;
  473. $posX=$sInfo[0]-$wInfo[0];
  474. //生成混合图像
  475. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  476. break;
  477. //左下
  478. case 3:
  479. $posY=$sInfo[1]-$wInfo[1];
  480. $posX=0;
  481. //生成混合图像
  482. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  483. break;
  484. //右下
  485. case 4:
  486. $posY=$sInfo[1]-$wInfo[1];
  487. $posX=$sInfo[0]-$wInfo[0];
  488. //生成混合图像
  489. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  490. break;
  491. //居中
  492. case 5:
  493. $posY=$sInfo[1]/2-$wInfo[1]/2;
  494. $posX=$sInfo[0]/2-$wInfo[0]/2;
  495. //生成混合图像
  496. imagecopymerge($sImage, $wImage, $posX, $posY, 0, 0, $wInfo[0],$wInfo[1],$alpha);
  497. break;
  498. }
  499. //如果没有给出保存文件名,默认为原图像名
  500. @unlink($source);
  501. //保存图像
  502. imagejpeg($sImage,$source,100);
  503. imagedestroy($sImage);
  504. }
  505. }
  506. if(!function_exists('image_type_to_extension'))
  507. {
  508. function image_type_to_extension($imagetype)
  509. {
  510. if(emptyempty($imagetype))
  511. return false;
  512. switch($imagetype)
  513. {
  514. case IMAGETYPE_GIF : return '.gif';
  515. case IMAGETYPE_JPEG : return '.jpeg';
  516. case IMAGETYPE_PNG : return '.png';
  517. case IMAGETYPE_SWF : return '.swf';
  518. case IMAGETYPE_PSD : return '.psd';
  519. case IMAGETYPE_BMP : return '.bmp';
  520. case IMAGETYPE_TIFF_II : return '.tiff';
  521. case IMAGETYPE_TIFF_MM : return '.tiff';
  522. case IMAGETYPE_JPC : return '.jpc';
  523. case IMAGETYPE_JP2 : return '.jp2';
  524. case IMAGETYPE_JPX : return '.jpf';
  525. case IMAGETYPE_JB2 : return '.jb2';
  526. case IMAGETYPE_SWC : return '.swc';
  527. case IMAGETYPE_IFF : return '.aiff';
  528. case IMAGETYPE_WBMP : return '.wbmp';
  529. case IMAGETYPE_XBM : return '.xbm';
  530. default : return false;
  531. }
  532. }
  533. }
  534. ?>

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,"",$is_preview);
  20. if(app_conf("PUBLIC_DOMAIN_ROOT")!='')
  21. {
  22. $paths = pathinfo($new_path);
  23. $path = str_replace("./","",$paths['dirname']);
  24. $filename = $paths['basename'];
  25. $pathwithoupublic = str_replace("public/","",$path);
  26. $file_data = @file_get_contents($path.$file);
  27. $img = @imagecreatefromstring($file_data);
  28. if($img!==false)
  29. {
  30. $save_path = "public/".$path;
  31. if(!is_dir($save_path))
  32. {
  33. @mk_dir($save_path);
  34. }
  35. @file_put_contents($save_path.$name,$file_data);
  36. }
  37. }
  38. }
  39. }
  40. return $new_path;
  41. }

3.使用方法:

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