FriendsOfCake / cakephp-upload

CakePHP: Handle file uploading sans ridiculous automagic
https://cakephp-upload.readthedocs.io/
MIT License
551 stars 255 forks source link

How to compress uploaded image? #504

Closed titamrtn closed 5 years ago

titamrtn commented 5 years ago

I upload a big image arround 15M. How can i compress it? I tried using transformer but it keep the original file

$this->addBehavior('Josegonzalez/Upload.Upload', [
            'photos' => [
                'path' => 'webroot{DS}img{DS}',
                'nameCallback' => function($data, $options = array()) {
                    $ext = pathinfo($data['name'], PATHINFO_EXTENSION);
                    return sha1(mt_rand(1, 9999) . uniqid()) . time() . '.' . $ext;
                },
                'fields' => [
                    'type' => 'file_type',
                ],
                'transformer' => function (\Cake\Datasource\RepositoryInterface $table, \Cake\Datasource\EntityInterface $entity, $data, $field, $settings) {

                    $imagine = new \Imagine\Gd\Imagine();
                    $imagine->open($data['tmp_name'])
                        ->save(WWW_ROOT . 'img' . DS . $data['name'], array('quality' => 40));
                    return [
                        $data['tmp_name'] => $data['name'],
                    ];
                }
            ]
        ]);
raul338 commented 5 years ago

You have to resize the image in another path (eg. temp path) and return in the array instead of the original

$imagine
    // ->.....
    ->save($tempPhotoPath);
return [
    $tempPhotoPath => $data['name'],
];