php 将图片保存为不同尺寸的图片类的简单示例

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

猜你在找的PHP相关文章