Image Intervention w/ Laravel 5.4 Storage

后端 未结 10 863
执笔经年
执笔经年 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:36

    You're trying to pass into putFile wrong object. That method expects File object (not Image).

    $path   = $request->file('createcommunityavatar');
    
    // returns \Intervention\Image\Image - OK
    $resize = Image::make($path)->fit(300);
    
    // expects 2nd arg - \Illuminate\Http\UploadedFile - ERROR, because Image does not have hashName method
    $store  = Storage::putFile('public/image', $resize);
    
    $url    = Storage::url($store);
    

    Ok, now when we understand the main reason, let's fix the code

    // returns Intervention\Image\Image
    $resize = Image::make($path)->fit(300)->encode('jpg');
    
    // calculate md5 hash of encoded image
    $hash = md5($resize->__toString());
    
    // use hash as a name
    $path = "images/{$hash}.jpg";
    
    // save it locally to ~/public/images/{$hash}.jpg
    $resize->save(public_path($path));
    
    // $url = "/images/{$hash}.jpg"
    $url = "/" . $path;
    

    Let's imagine that you want to use Storage facade:

    // does not work - Storage::putFile('public/image', $resize);
    
    // Storage::put($path, $contents, $visibility = null)
    Storage::put('public/image/myUniqueFileNameHere.jpg', $resize->__toString());
    

提交回复
热议问题