首页 > 后端开发 > php教程 > 将图片保存为不同规格的图片的php代码

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

WBOY
发布: 2016-07-25 09:03:39
原创
873 人浏览过
  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"] return false;
  388. if(is_animated_gif($source))
  389. {
  390. require_once APP_ROOT_PATH."system/utils/gif_encoder.php";
  391. require_once APP_ROOT_PATH."system/utils/gif_reader.php";
  392. $gif = new GIFReader();

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

  473. if(!function_exists($wCreateFun))
  474. $wCreateFun = 'imagecreatefromjpeg';
  475. $wImage=$wCreateFun($water);
  476. //设定图像的混色模式

  477. imagealphablending($wImage, true);
  478. switch (intval($position))

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

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

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

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

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
  5. =get_spec_image($data['image'],120,120,0);
  6. $big_url=get_spec_image($data['image'],200,200,0);
复制代码


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板