85 lines
2.5 KiB
PHP
85 lines
2.5 KiB
PHP
|
<?php
|
||
|
|
||
|
use Intervention\Image\ImageManager;
|
||
|
|
||
|
class ImageProcessor {
|
||
|
private $manager;
|
||
|
private $uploadPath;
|
||
|
|
||
|
public function __construct() {
|
||
|
$this->manager = new ImageManager(['driver' => 'gd']);
|
||
|
$this->uploadPath = __DIR__ . '/../uploads';
|
||
|
}
|
||
|
|
||
|
public function process($file, $type = 'product', $width = 800, $height = null) {
|
||
|
// Validate file
|
||
|
if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
|
||
|
throw new Exception('No file uploaded');
|
||
|
}
|
||
|
|
||
|
// Create type directory if it doesn't exist
|
||
|
$targetDir = $this->uploadPath . '/' . $type;
|
||
|
if (!file_exists($targetDir)) {
|
||
|
mkdir($targetDir, 0755, true);
|
||
|
}
|
||
|
|
||
|
// Generate unique filename
|
||
|
$filename = uniqid() . '_' . time() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
|
||
|
$targetPath = $targetDir . '/' . $filename;
|
||
|
|
||
|
// Process image
|
||
|
$image = $this->manager->make($file['tmp_name']);
|
||
|
|
||
|
// Resize image
|
||
|
if ($height) {
|
||
|
$image->fit($width, $height, function ($constraint) {
|
||
|
$constraint->aspectRatio();
|
||
|
$constraint->upsize();
|
||
|
});
|
||
|
} else {
|
||
|
$image->resize($width, null, function ($constraint) {
|
||
|
$constraint->aspectRatio();
|
||
|
$constraint->upsize();
|
||
|
});
|
||
|
}
|
||
|
|
||
|
// Optimize and save
|
||
|
$image->save($targetPath, 85);
|
||
|
|
||
|
// Create thumbnail
|
||
|
$this->createThumbnail($image, $type, $filename);
|
||
|
|
||
|
return [
|
||
|
'filename' => $filename,
|
||
|
'path' => $type . '/' . $filename,
|
||
|
'thumbnail' => $type . '/thumbnails/' . $filename
|
||
|
];
|
||
|
}
|
||
|
|
||
|
private function createThumbnail($image, $type, $filename) {
|
||
|
$thumbDir = $this->uploadPath . '/' . $type . '/thumbnails';
|
||
|
if (!file_exists($thumbDir)) {
|
||
|
mkdir($thumbDir, 0755, true);
|
||
|
}
|
||
|
|
||
|
$image->fit(200, 200, function ($constraint) {
|
||
|
$constraint->aspectRatio();
|
||
|
})->save($thumbDir . '/' . $filename, 85);
|
||
|
}
|
||
|
|
||
|
public function delete($path) {
|
||
|
$fullPath = $this->uploadPath . '/' . $path;
|
||
|
if (file_exists($fullPath)) {
|
||
|
unlink($fullPath);
|
||
|
|
||
|
// Delete thumbnail if exists
|
||
|
$thumbPath = dirname($fullPath) . '/thumbnails/' . basename($fullPath);
|
||
|
if (file_exists($thumbPath)) {
|
||
|
unlink($thumbPath);
|
||
|
}
|
||
|
return true;
|
||
|
}
|
||
|
return false;
|
||
|
}
|
||
|
}
|