Last active
September 25, 2020 23:34
-
-
Save ozero/62b105567640d849f3a990fa4725c4e5 to your computer and use it in GitHub Desktop.
Humhub: Reduce filesize of attached image.
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 | |
/* | |
# Reduce filesize of attached image. | |
- for X or Y axis: 1024px max | |
- compress into Jpeg on q=90 | |
## Usage | |
1. Place me on `/protected/humhub/modules/local/libs` | |
2. Add a line to call me at `protected function handleFileUpload` on `humhub\modules\file\actions\UploadAction.php`. | |
## Example | |
protected function handleFileUpload(UploadedFile $uploadedFile, $hideInStream = false) | |
{ | |
//Reduce filesize of attached image. | |
$uploadedFile = \humhub\modules\local\libs\Reduce::Resize($uploadedFile); | |
*/ | |
namespace humhub\modules\local\libs; | |
use yii\imagine\Image; | |
use Imagine\Gd; | |
use Imagine\Image\Box; | |
use Imagine\Image\BoxInterface; | |
class Reduce { | |
public static function Resize($uploadedFile) { | |
$_limit = 1024;//reduce to this pixel size | |
$_quality = 90;//Jpeg quality on compression | |
//process only images | |
$filetype = $uploadedFile->type; | |
if(strpos($filetype,'image/') === false){ | |
return $uploadedFile; | |
} | |
// gif: store as-is | |
if(strpos($filetype,'gif') !== false){ | |
return $uploadedFile; | |
} | |
$filepath = $uploadedFile->tempName; | |
Image::getImagine() | |
->open($filepath) | |
->thumbnail(new Box($_limit, $_limit)) | |
->save($filepath , ['quality' => $_quality]); | |
$uploadedFile->size = filesize($filepath); | |
//png: convert to jpg | |
if(strpos($filetype,'png') !== false){ | |
$imagePng = imagecreatefrompng($filepath); | |
imagejpeg($imagePng, $filepath, $_quality); | |
imagedestroy($imagePng); | |
//update type & size | |
$uploadedFile->type = "image/jpeg"; | |
$uploadedFile->size = filesize($filepath); | |
//add ".jpg" to name | |
$uploadedFile->name = $uploadedFile->name.".jpg"; | |
} | |
return $uploadedFile; | |
} | |
} |
Ref: Reduce the size of the original uploaded files (advice) · Issue #1340 · humhub/humhub
humhub/humhub#1340
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Original: http://laravel.hatenablog.com/entry/2018/07/28/021839
(Change: using
Imagine
instead ofImageConverter
, for Humhub 1.5.0-beta.1 (April 6, 2020) Enh #3402 )