Qlic's avatar
Level 18

Uploading image using Storage and creating thumbnail using Image

With some help from laracasts members i managed to get my uploader to store images inside the local storage folder. However, the next step is to create a thumbnail for all uploaded images. For this i use the Intervention Image package.

The problem i'm having is the following, i can't get it to store inside the storage folder. Upon uploading, the image i store it with the Storage::put() command.

When creating a thumbnail, i have to use the $img->save(); command, in which i have to define the output path/file.

I can't figure out what the path to the storage folder is.

if (Request::hasFile('attachments'))
{
    foreach (Request::file('attachments') as $file)
    {
        $fileName = time() .'_'. md5($file->getClientOriginalName()) .'.'. $file->getClientOriginalExtension();
        Storage::put('project/'. $id .'/'. $fileName, file_get_contents($file));
        ProjectAttachment::create(['project_id' => $id, 'name' => $fileName]);

        if (substr(File::mimeType($file), 0, 5) == 'image')
        {
            $this->attachmentThumb(file_get_contents($file), $id, $fileName, 100, 100);
        }
    }
}
public function attachmentThumb($input, $id, $name, $width, $height)
{
    // create new image with transparent background color
    $background = \Image::canvas($width, $height);
    // read image file and resize it
    // but keep aspect-ratio and do not size up,
    // so smaller sizes don't stretch
    $image = \Image::make($input)->resize($width, $height, function ($c) {
        $c->aspectRatio();
        $c->upsize();
    });
    // insert resized image centered into background
    $background->insert($image, 'center');
    // save
    $background->save('project/'. $id .'/thumb_'. $name);
    
    // I also tried: $background->save('storage/app/project/'. $id .'/thumb_'. $name);
}
0 likes
5 replies
Qlic's avatar
Qlic
OP
Best Answer
Level 18

Turns out i needed: $background->save('../storage/app/project/'. $id .'/thumb_'. $name);

1 like
martinbean's avatar

@Qlic You can shorten that by using the storage_path helper:

$background->save(storage_path().'/app/project/'. $id .'/thumb_'. $name);
Qlic's avatar
Level 18

@martinbean i looked at storage_path() but made the path something along the lines of : c:\wamp\www\project/storage/app/project/1/file.jpg

martinbean's avatar

@Qlic It would if you’re using Windows, as Windows uses a backslash for directory separators.

Please or to participate in this conversation.