Use LiipImagineBundle to Resize Image after Upload?

后端 未结 5 453
梦毁少年i
梦毁少年i 2020-12-02 21:08

I\'m using the LiipImagineBundle with Symfony 2.1 and would like to resize user uploaded images upon upload before saving them to the permanent filesystem location (to strip

5条回答
  •  盖世英雄少女心
    2020-12-02 21:40

    Given that I did not find a better way, I kept the solution described in the question description. That solution does not seem the optimal one from a performance stand point (it requires moving the file twice, apply the filter once, and unlink 1 file), but it gets the job accomplished.

    UPDATE:

    I changed my code to use the services indicated in Peter Wooster's answer, as shown below (that solution is more optimal as the filtered image is saved directly to the final destination):

    class MyController extends Controller
    {
        public function new_imageAction(Request $request)
        {
            $uploadedFile = $request->files->get('file');
            // ...get file extension and do other validation...
            $tmpFolderPathAbs = $this->get('kernel')->getRootDir() . '/../web/uploads/tmp/'; // folder to store unfiltered temp file
            $tmpImageNameNoExt = rand();
            $tmpImageName = $tmpImageNameNoExt . '.' . $fileExtension;
            $uploadedFile->move($tmpFolderPathAbs, $tmpImageName);
            $tmpImagePathRel = '/uploads/tmp/' . $tmpImageName;
            // Create the filtered image:
            $processedImage = $this->container->get('liip_imagine.data.manager')->find('my_filter', $tmpImagePathRel);
            $filteredImage = $this->container->get('liip_imagine.filter.manager')->get($request, 'my_filter', $processedImage, $tmpImagePathRel)->getContent();
            unlink($tmpFolderPathAbs . $tmpImageName); // eliminate unfiltered temp file.
            $permanentFolderPath = $this->get('kernel')->getRootDir() . '/../web/uploads/path_to_folder/';
            $permanentImagePath = $permanentFolderPath . 'my_image.jpeg';
            $f = fopen($permanentImagePath, 'w');
            fwrite($f, $filteredImage); 
            fclose($f);
        }
    }
    

提交回复
热议问题