Created
February 1, 2016 18:41
-
-
Save samnabi/f4ecb351f2ec2bd596e5 to your computer and use it in GitHub Desktop.
Kirby v2: Shrink large images on upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Copy this code into your config.php file | |
// Replace the default $maxDimension to meet your needs | |
// Read more about Kirby's Panel hooks at https://getkirby.com/docs/panel/developers/hooks | |
// Shrink large images on upload | |
kirby()->hook('panel.file.upload', 'shrinkImage'); | |
kirby()->hook('panel.file.replace', 'shrinkImage'); | |
function shrinkImage($file, $maxDimension = 1000) { | |
try { | |
if ($file->type() == 'image' and ($file->width() > $maxDimension or $file->height() > $maxDimension)) { | |
// Get original file path | |
$originalPath = $file->dir().'/'.$file->filename(); | |
// Create a thumb and get its path | |
$resized = $file->resize($maxDimension,$maxDimension); | |
$resizedPath = $resized->dir().'/'.$resized->filename(); | |
// Replace the original file with the resized one | |
copy($resizedPath, $originalPath); | |
unlink($resizedPath); | |
} | |
} catch(Exception $e) { | |
return response::error($e->getMessage()); | |
} | |
} | |
?> |
How to keep the two images ? The original and the thumb, with different name ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@samnabi in replace hook there must be another variable.
Changing line 10 solves the problem:
function shrinkImage($file, $oldFile, $maxDimension = 1000) {