|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
-
- namespace Modules;
-
- class CachedImage {
-
- public $original;
- public $cache_dir = "tmp/";
- public $default_width = 500;
- public $format;
- public $quality;
- private $usecache = true;
-
- function __construct($path,$format=false) {
- $f3 = \Base::instance();
- $this->original = $path;
- $this->format = $f3->get('cachedImageFormat') ? : 'jpeg';
- $this->quality = $f3->get('cachedImageQuality') ? : false;
-
- if (is_string($format)) {
- $format = strtolower($format);
- if (in_array($format, ['png','jpg','jpeg'])) {
- $this->format = $format;
- } elseif ($format == "nocache") {
- $this->usecache = false;
- }
- }
-
- if ($this->quality === false) {
- switch($this->format) {
- case 'png':
- $this->quality = 6;
- break;
- case 'jpg':
- case 'jpeg':
- $this->quality = 75;
- break;
- }
- }
- }
-
- function get_src($inwidth = false) {
- $f3 = \Base::instance();
- if($this->is_image($this->original) && $this->usecache) {
- $info = pathinfo($this->original);
- $fn = basename($this->original,'.'.$info['extension']);
- $width = $inwidth ? $inwidth : $this->default_width;
- $name = md5($this->original.$width);
-
- $name = sprintf("%s_%s.%s",$fn,$name,$this->format);
-
- $out = $this->cache_dir.$name;
-
- //if(!file_exists($this->original)) { $this->original='rsc/img/default.png'; }
-
- if(!file_exists($out)) {
- $img1 = new \Image($this->original);
- $img1->resize($width);
- $f3->write($out,$img1->dump($this->format,$this->quality));
- unset($img1);
- }
- } else {
- $out = $this->original;
- }
- return "/".$out;
- }
-
- function is_image($path) {
- // this protects from accidently calling this class on a wrong file
- // it doesn't ensure that the file actually contains valid image data
- $ex = explode('.',$path);
- $ext = array_pop($ex);
- return in_array(strtolower($ext),array( 'jpg', 'jpeg', 'png' ));
- }
- }
|