Laravel 4上传1张图片并保存为多张(3)

时间:2014-03-01 14:31:34

标签: image upload laravel

我正在尝试用laravel 4创建一个图像上传脚本。(使用资源控制器),我正在使用包干预图像。

我想要的是:上传图片时将其保存为3个不同的图像(不同尺寸)。

例如:

1-FOO-original.jpg

1-FOO-thumbnail.jpg

1-FOO-resized.jpg

这是我到目前为止所做的......它不起作用或任何东西,但这是我可以得到它。

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

希望有人可以帮助我,谢谢!

2 个答案:

答案 0 :(得分:8)

你可以试试这个:

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

答案 1 :(得分:6)

试试这个

$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();