php根据url自动生成缩略图(附源码)

原创
2016-07-25 08:55:28 1192浏览
  1. sudo a2enmod rewrite
复制代码

2,.htaccess文件的内容:

  1. RewriteEngine On
  2. # '-s' (is regular file, with size)
  3. # '-l' (is symbolic link)
  4. # '-d' (is directory)
  5. # 'ornext|OR' (or next condition)
  6. # 'nocase|NC' (no case)
  7. # 'last|L' (last rule)
  8. RewriteCond %{REQUEST_FILENAME} -s [OR]
  9. RewriteCond %{REQUEST_FILENAME} -l [OR]
  10. RewriteCond %{REQUEST_FILENAME} -d
  11. RewriteRule ^.*$ - [NC,L]
  12. RewriteRule ^.*$ createthumb.php?path=%{REQUEST_URI} [NC,L]
复制代码

有关htaccess文件的配置方法,请参考: apache .htaccess配置详解 .htaccess配置详解(全面经典不容错过) .htaccess文件使用总结 .htaccess教程.htaccess学习总结 Apache使用.htaccess配置伪静态的例子 htaccess伪静态规则配置的几个例子 探讨:htaccess URL重写rewrite与重定向redirect 3,createthumb.php

  1. define('WWW_PATH', dirname(dirname(__FILE__))); // 站点www目录
  2. require(WWW_PATH.'/PicThumb.class.php'); // include PicThumb.class.php
  3. require(WWW_PATH.'/ThumbConfig.php'); // include ThumbConfig.php
  4. $logfile = WWW_PATH.'/createthumb.log'; // 日志文件
  5. $source_path = WWW_PATH.'/upload/'; // 原路径
  6. $dest_path = WWW_PATH.'/supload/'; // 目标路径
  7. $path = isset($_GET['path'])? $_GET['path'] : ''; // 访问的图片URL
  8. // 检查path
  9. if(!$path){
  10. exit();
  11. }
  12. // 获取图片URI
  13. $relative_url = str_replace($dest_path, '', WWW_PATH.$path);
  14. // 获取type
  15. $type = substr($relative_url, 0, strpos($relative_url, '//m.sbmmt.com/m/'));
  16. // 获取config
  17. $config = isset($thumb_config[$type])? $thumb_config[$type] : '';
  18. // 检查config
  19. if(!$config || !isset($config['fromdir'])){
  20. exit();
  21. }
  22. // 原图文件
  23. $source = str_replace('//m.sbmmt.com/m/'.$type.'//m.sbmmt.com/m/', '//m.sbmmt.com/m/'.$config['fromdir'].'//m.sbmmt.com/m/', $source_path.$relative_url);
  24. // 目标文件
  25. $dest = $dest_path.$relative_url;
  26. // 创建缩略图
  27. $obj = new PicThumb($logfile);
  28. $obj->set_config($config);
  29. if($obj->create_thumb($source, $dest)){
  30. ob_clean();
  31. header('content-type:'.mime_content_type($dest));
  32. exit(file_get_contents($dest));
  33. }
  34. ?>
复制代码

4,ThumbConfig.php

  1. $thumb_config = array(
  2. 'news' => array(
  3. 'fromdir' => 'news', // 来源目录
  4. 'type' => 'fit',
  5. 'width' => 100,
  6. 'height' => 100,
  7. 'bgcolor' => '#FF0000'
  8. ),
  9. 'news_1' => array(
  10. 'fromdir' => 'news',
  11. 'type' => 'fit',
  12. 'width' => 200,
  13. 'height' => 200,
  14. 'bgcolor' => '#FFFF00'
  15. ),
  16. 'article' => array(
  17. 'fromdir' => 'article',
  18. 'type' => 'crop',
  19. 'width' => 250,
  20. 'height' => 250,
  21. 'watermark' => WWW_PATH.'/supload/watermark.png'
  22. )
  23. );
  24. ?>
复制代码

例如,访问这三个路径后会按config自动生成缩略图

http://localhost/supload/news/2013/07/21/1.jpg http://localhost/supload/news_1/2013/07/21/1.jpg http://localhost/supload/article/2013/07/21/2.jpg

附,php根据url自动生成缩略图的源码下载地址



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。