jfs

createLandscape

jfs
Apr 24th, 2019
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.50 KB | None | 0 0
  1. kirby()->hook('panel.file.upload', function($file) {
  2.     try {
  3.         list($width, $height) = getimagesize($file->width());
  4.         if ($width > $height) {
  5.             // Landscape
  6.             $file->resize(1200, 800);
  7.         } else {
  8.             // Portrait or Square
  9.             createLandscape($file->url());
  10.         }
  11.     } catch (Exception $e) {
  12.         throw new Exception($e->getMessage());
  13.     }
  14. });
  15.  
  16. function createLandscape($filePath){
  17.     //$filePath = '003.jpg';  //full path to your png, including filename and extension
  18.     $fileParts = pathinfo($filePath);
  19.     $savePath = $filePath;  //full path to saved png, including filename and extension
  20.     $colorRgb = ['red' => 229, 'green' => 231, 'blue' => 232];  //background color
  21.  
  22.     if($fileParts['extension'] == 'jpg' || $fileParts['extension'] == 'jpeg'){
  23.         $img = @imagecreatefromjpeg($filePath);
  24.         $imgWidth = imagesx($img);
  25.         $imgHeight = imagesy($img);
  26.         $width  = 1200;
  27.         $height = 810;
  28.         $endPosX = ($width - $imgWidth) / 2;
  29.     }
  30.  
  31.     //create new image and fill with background color
  32.     $backgroundImg = @imagecreatetruecolor($width, $height);
  33.  
  34.     $color = imagecolorallocate($backgroundImg, $colorRgb['red'], $colorRgb['green'], $colorRgb['blue']);
  35.     imagefill($backgroundImg, 0, 0, $color);
  36.  
  37.     //copy original image to background
  38.     imagecopy($backgroundImg, $img, $endPosX, 0, 0, 0, $imgWidth, $imgHeight);
  39.  
  40.     //save as jpg
  41.     imagejpeg($backgroundImg, $savePath, 100);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment