-
Notifications
You must be signed in to change notification settings - Fork 0
/
Thumbnailer.class.php
executable file
·95 lines (78 loc) · 2.67 KB
/
Thumbnailer.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
require_once("Logger.class.php");
class Thumbnailer {
protected $base_dir;
protected $thumb_base;
protected $logger;
public function __construct($base_dir) {
$this->base_dir = $base_dir;
$this->thumb_base = $this->base_dir."/thumbnails";
$date = date("Y-m-d");
$log_file = "/mine/scripts/logs/".__CLASS__."_{$date}.log";
$this->logger = new Logger($log_file);
}
public function getThumbDir($file) {
$file_info = pathinfo($file);
$thumb_dir = str_replace($this->base_dir, $this->thumb_base, $file_info['dirname']);
if(!file_exists($thumb_dir)) {
mkdir($thumb_dir, 0777, true);
}
return $thumb_dir;
}
public function generateThumb($file) {
if(stristr($file, $this->thumb_base)) {
$this->logger->addToLog("File provided is in the thumbnail dir: [{$file}]");
return false;
}
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
$thumb_dir = $this->getThumbDir($file);
$file_parts = explode("/", $file);
$file_name = end($file_parts);
$thumbnail = $thumb_dir . "/" . $file_name;
if (!file_exists($thumbnail)) {
if (file_exists($file)) {
$this->logger->addToLog("Generating thumbnail from [{$file}] to [{$thumbnail}]");
list($width, $height) = getimagesize($file);
$new_height = 150;
$new_width = $width / ($height / $new_height);
if (in_array($ext, array("jpg", "jpeg"))) {
$methods = array("imagecreatefrom" => "imagecreatefromjpeg", "image" => "imagejpeg");
$quality = 100;
} elseif ($ext == "png") {
$methods = array("imagecreatefrom" => "imagecreatefrompng", "image" => "imagepng");
$quality = 9;
} elseif ($ext == "gif") {
$methods = array("imagecreatefrom" => "imagecreatefromgif", "image" => "imagegif");
$quality = 100;
}
// Load the images
$thumb = imagecreatetruecolor($new_width, $new_height);
if (!$thumb) {
$this->logger->addToLog("imagecreatetruecolor failed");
return false;
}
$source = $methods["imagecreatefrom"]($file);
if (!$source) {
$this->logger->addToLog("{$methods["imagecreatefrom"]} failed");
return false;
}
// Resize the $thumb image.
if (imagecopyresized($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height)) {
// Save the new file to the location specified by $thumbnail
if (!$methods["image"]($thumb, $thumbnail, $quality)) {
$this->logger->addToLog("{$methods["image"]} FAILED to generate thumbnail... [{$thumbnail}]");
return false;
}
} else {
$this->logger->addToLog("imagecopyresized failed");
return false;
}
} else {
$this->logger->addToLog("File [{$file}] does not exist...");
return false;
}
}
return true;
}
}
?>