Image Intervention w/ Laravel 5.4 Storage

后端 未结 10 845
执笔经年
执笔经年 2021-02-05 03:16

I\'m using the storage facade to store a avatar which works fine, but I want to resize my image like I did in previous versions of laravel. How can I go about doing this? Here i

10条回答
  •  说谎
    说谎 (楼主)
    2021-02-05 03:51

    Using Laravel 5.8

    I had a similar issue when trying to read an image file with Image when this one was saved and loaded with Storage.
    Beside all the answers I wasn't sure why it wasn't working.


    Exception when Image was trying to read the file

    Intervention\Image\Exception\NotReadableException : Unable to init from given binary data.

    Short answer

    Adding ->encode()solved the issue

    http://image.intervention.io/api/encode

    Scenario

    Basically I had a test like this

    Storage::fake();
    
    $photo = factory(Photo::class)->create();    
    $file = \Image::make(
        UploadedFile::fake()->image($photo->file_name, 300, 300)
    );
    
    Storage::disk($photo->disk)
        ->put(
            $photo->fullPath(),
            $file
        );
    

    And in the controller I had something like this

    return \Image::make(
        Storage::disk($photo->disk)
            ->get(
                $photo->fullPath()
            )
    )->response();
    

    Solution

    After investigation I realized that any file created by Image and saved by the Storage had a size of 0 octets. After looking at all the solutions from this post and few hours after, I noticed everyone was using encode() but no one did mention it was that. So I tried and it worked.

    Investigating a bit more, Image does, in fact, encode under the hood before saving. https://github.com/Intervention/image/blob/master/src/Intervention/Image/Image.php#L146

    So, my solution was to simple doing this

    $file = \Image::make(
        \Illuminate\Http\UploadedFile::fake()->image('filename.jpg', 300, 300)
    )->encode();
    
    \Storage::put('photos/test.jpg', $file);
    

    testable in Tinker, It will create a black image

提交回复
热议问题