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

瘦欲@ 提交于 2020-01-01 03:16:30

问题


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!


回答1:


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);
}



回答2:


Try this

$file = Input::file('userfile');
$fileName = Str::random(4).'.'.$file->getClientOriginalExtension();
$destinationPath    = 'your upload image folder';

// upload new image
Image::make($file->getRealPath())
// original
->save($destinationPath.'1-foo-original'.$fileName)
// thumbnail
->grab('100', '100')
->save($destinationPath.'1-foo-thumbnail'.$fileName)
// resize
->resize('280', '255', true) // set true if you want proportional image resize
->save($destinationPath.'1-foo-resize-'.$fileName)
->destroy();


来源:https://stackoverflow.com/questions/22115607/laravel-4-upload-1-image-and-save-as-multiple-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!