Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 upload 1 image and save as multiple (3)

I'm trying to make an image upload script with laravel 4. (using Resource Controller) and i'm using the package Intervention Image.

And what i want is: when uploading an image to save it as 3 different images (different sizes).

for example:

1-foo-original.jpg

1-foo-thumbnail.jpg

1-foo-resized.jpg

This is what i got so far.. it's not working or anything, but this was as far as i could get with it.

if(Input::hasFile('image')) {
     $file             = Input::file('image');
     $fileName         = $file->getClientOriginalName();
     $fileExtension    = $file->getClientOriginalExtension();
     $type = ????;

     $newFileName = '1' . '-' . $fileName . '-' . $type . $fileExtension;

     $img =  Image::make('public/assets/'.$newFileName)->resize(300, null, true);
     $img->save();
}

Hopefully someone can help me out, thanks!

like image 293
yinshiro Avatar asked Mar 01 '14 14:03

yinshiro


1 Answers

You may try this:

$types = array('-original.', '-thumbnail.', '-resized.');
// Width and height for thumb and resized
$sizes = array( array('60', '60'), array('200', '200') );
$targetPath = 'images/';

$file = Input::file('file')[0];
$fname = $file->getClientOriginalName();
$ext = $file->getClientOriginalExtension();
$nameWithOutExt = str_replace('.' . $ext, '', $fname);

$original = $nameWithOutExt . array_shift($types) . $ext;
$file->move($targetPath, $original); // Move the original one first

foreach ($types as $key => $type) {
    // Copy and move (thumb, resized)
    $newName = $nameWithOutExt . $type . $ext;
    File::copy($targetPath . $original, $targetPath . $newName);
    Image::make($targetPath . $newName)
          ->resize($sizes[$key][0], $sizes[$key][1])
          ->save($targetPath . $newName);
}
like image 57
The Alpha Avatar answered Nov 15 '22 05:11

The Alpha