且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

上传后使用 LiipImagineBundle 调整图像大小?

更新时间:2023-01-15 12:17:41

这里提供了一种使用 LiipImagineBundle 在上传时创建缩略图的方法.诀窍是使用他们的一些其他服务:

So here's a way to create thumbnails at upload with LiipImagineBundle. The trick is to use some of their other services:

    /**
     * Write a thumbnail image using the LiipImagineBundle
     * 
     * @param Document $document an Entity that represents an image in the database
     * @param string $filter the Imagine filter to use
     */
    private function writeThumbnail($document, $filter) {
        $path = $document->getWebPath();                                // domain relative path to full sized image
        $tpath = $document->getRootDir().$document->getThumbPath();     // absolute path of saved thumbnail

        $container = $this->container;                                  // the DI container
        $dataManager = $container->get('liip_imagine.data.manager');    // the data manager service
        $filterManager = $container->get('liip_imagine.filter.manager');// the filter manager service

        $image = $dataManager->find($filter, $path);                    // find the image and determine its type
        $response = $filterManager->get($this->getRequest(), $filter, $image, $path); // run the filter 
        $thumb = $response->getContent();                               // get the image from the response

        $f = fopen($tpath, 'w');                                        // create thumbnail file
        fwrite($f, $thumb);                                             // write the thumbnail
        fclose($f);                                                     // close the file
    }

如果您没有其他理由包含 LiipImagineBundle,这也可以通过直接调用 Imagine 库函数来完成.我可能会在未来研究这个问题,但这对我的情况很有效,并且表现非常好.

This could also be done by directly calling the Imagine library functions if you had no other reason to include the LiipImagineBundle. I'll probably look into that in the future, but this works for my case and performs very well.