FriendsOfCake/cakephp-upload

How to compress uploaded image?

titamrtn opened this issue · 1 comments

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'],
                    ];
                }
            ]
        ]);

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'],
];