40 lines
1.5 KiB
PHP
40 lines
1.5 KiB
PHP
<?php
|
|
|
|
use Config\Services;
|
|
|
|
if (!function_exists('save_image_with_compression')) {
|
|
/**
|
|
* Save original image and a compressed (resized) version.
|
|
*
|
|
* @param \CodeIgniter\HTTP\Files\UploadedFile $uploadedFile
|
|
* @param string $originalPath Folder for original image
|
|
* @param string $compressedPath Folder for compressed image
|
|
* @param int $compressedWidth Target width for compressed image
|
|
* @param int $quality JPEG quality (0-100)
|
|
* @return array ['original' => ..., 'compressed' => ...]
|
|
*/
|
|
function save_image_with_compression($uploadedFile, $originalPath, $compressedPath, $compressedWidth = 900, $quality = 80)
|
|
{
|
|
// Make sure directories exist
|
|
if (!is_dir($originalPath)) mkdir($originalPath, 0755, true);
|
|
if (!is_dir($compressedPath)) mkdir($compressedPath, 0755, true);
|
|
|
|
// Save original image
|
|
$newName = $uploadedFile->getRandomName();
|
|
$uploadedFile->move($originalPath, $newName);
|
|
$originalImage = rtrim($originalPath, '/\\') . '/' . $newName;
|
|
|
|
// Resize and compress
|
|
$imageService = Services::image('gd'); // or 'imagick' if enabled
|
|
$imageService
|
|
->withFile($originalImage)
|
|
->resize($compressedWidth, 0, true) // keep aspect ratio
|
|
->save(rtrim($compressedPath, '/\\') . '/' . $newName, $quality);
|
|
|
|
return [
|
|
'original' => $originalImage,
|
|
'compressed' => rtrim($compressedPath, '/\\') . '/' . $newName,
|
|
];
|
|
}
|
|
}
|