Skip to content

Instantly share code, notes, and snippets.

@ozero
Last active September 25, 2020 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozero/62b105567640d849f3a990fa4725c4e5 to your computer and use it in GitHub Desktop.
Save ozero/62b105567640d849f3a990fa4725c4e5 to your computer and use it in GitHub Desktop.
Humhub: Reduce filesize of attached image.
<?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;
}
}
@ozero
Copy link
Author

ozero commented Sep 7, 2020

Original: http://laravel.hatenablog.com/entry/2018/07/28/021839
(Change: using Imagine instead of ImageConverter, for Humhub 1.5.0-beta.1 (April 6, 2020) Enh #3402 )

@ozero
Copy link
Author

ozero commented Sep 7, 2020

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