Silverstripe 3.1 - resize image on upload

痞子三分冷 提交于 2019-12-23 02:56:18

问题


I want to resize the images while uploading them to save storrage. I tried it like this

            $visual = new UploadField('Visual', _t('Dict.PREVIEW_IMAGE', 'Preview Image'));
        $visual->setAllowedExtensions(array('jpg', 'jpeg', 'png', 'gif'));
        $visual->setFolderName('news/' .  $this->ID);
        $visual->resizeByHeight(10);

but the result was an whitescreen in the backend.

Is it possible to resize the images on upload? What am I doing wrong?

thank you in advance


回答1:


Before you read the answer, please rethink this issue. Do you have a reason why you would want to resize on upload?
I actually want my sites to store the full images, and display a resized copy of the image.
This way, if you later decide to display the images in a bigger size, you just change the resize code, and it will still look good. if you resize on upload, your images are already small, if you now change your website to display bigger ones, you will have to re-upload all images.


$visual is a UploadField, it has no resize capabilities. and no method called resizeByHeight, so the whitescreen is probably because you are calling a method that does not exist, and your error reporting is turned off.

resize methods are on the Image class, but they always make a copy of the file, so they do not resize the image itself, but instead save a resized copy of that image in the _resampled folder.

there is currently no functionality built in to actually resize the original image. however it should be fairly simple to implement by sub classing UploadField and overwriting either the method upload or one of the methods it uses to save the file.

A working example I just built:

class MyUploadField extends UploadField {
    protected function saveTemporaryFile($tmpFile, &$error = null) {
        $file = parent::saveTemporaryFile($tmpFile, $error);
        if ($file && is_a($file, 'Image')) {
            // only attempt to resize if it's an image
            $filePath = Director::baseFolder() . "/" . $file->Filename;
            // create a backend (either GDBackend or ImagickBackend depending on your settings)
            $backend = Injector::inst()->createWithArgs(Image::get_backend(), array($filePath));
            if ($backend->hasImageResource() && $backend->getHeight() > 100) {
                // if it is a working image and is higher than 100px, resize it to 100px height
                $newBackend = $backend->resizeByHeight(100);
                if ($newBackend) {
                    // resize successful, overwrite the existing file
                    $newBackend->writeTo($filePath);
                }
            }
        }
        return $file;
    }
}


来源:https://stackoverflow.com/questions/20713700/silverstripe-3-1-resize-image-on-upload

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!