80 lines
2.1 KiB
PHP
80 lines
2.1 KiB
PHP
<?php
|
|
|
|
class thumb {
|
|
protected string $imagedir;
|
|
protected string $thumbdir;
|
|
protected string $thumburl;
|
|
|
|
protected int $w = 200;
|
|
protected int $h = 200;
|
|
|
|
const IMAGE_HANDLERS = [
|
|
IMAGETYPE_JPEG => [
|
|
'load' => 'imagecreatefromjpeg',
|
|
],
|
|
IMAGETYPE_PNG => [
|
|
'load' => 'imagecreatefrompng',
|
|
],
|
|
IMAGETYPE_GIF => [
|
|
'load' => 'imagecreatefromgif',
|
|
],
|
|
IMAGETYPE_WEBP => [
|
|
'load' => 'imagecreatefromwebp',
|
|
]
|
|
];
|
|
|
|
public function __construct($idir, $tdir, $turl, $width, $heigth) {
|
|
$this->imagedir = $idir;
|
|
$this->thumbdir = $tdir;
|
|
$this->thumburl = $turl;
|
|
$this->w = $width;
|
|
$this->h = $heigth;
|
|
}
|
|
|
|
public function get_thumb($iname) {
|
|
$src = $this->imagedir.$iname;
|
|
$dstname = hash('sha256', $src);
|
|
$dstpath = $this->thumbdir.$dstname.'.jpg';
|
|
|
|
if (!file_exists($dstpath)) {
|
|
$type = exif_imagetype($src);
|
|
if ($type == 0) {
|
|
error_log("$src: Unknown Image Type");
|
|
return "img/error.png";
|
|
}
|
|
|
|
$image = call_user_func(self::IMAGE_HANDLERS[$type]['load'], $src);
|
|
|
|
if ($image == false) {
|
|
error_log("$src: Image Loading Failed");
|
|
return "img/error.png";
|
|
}
|
|
|
|
$srcwidth = imagesx($image);
|
|
$srcheight = imagesy($image);
|
|
|
|
|
|
$ratio = min($this->w / $srcwidth, $this->h / $srcheight);
|
|
$width = round($srcwidth*$ratio);
|
|
$height = round($srcheight*$ratio);
|
|
|
|
$thumbnail = imagecreatetruecolor($width, $height);
|
|
|
|
if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {
|
|
imagecolortransparent($thumbnail, imagecolorallocate($thumbnail, 0, 0, 0));
|
|
if ($type == IMAGETYPE_PNG) {
|
|
imagealphablending($thumbnail, false);
|
|
imagesavealpha($thumbnail, true);
|
|
}
|
|
}
|
|
|
|
imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $width, $height, $srcwidth, $srcheight);
|
|
call_user_func('imagejpeg',$thumbnail,$dstpath,100);
|
|
imagedestroy($image);
|
|
imagedestroy($thumbnail);
|
|
}
|
|
return $this->thumburl.$dstname.'.jpg';
|
|
}
|
|
}
|
|
|
|
?>
|