2014-03-01 51 views
6

我正在尝试使用laravel 4制作图像上传脚本(使用资源控制器),并使用了包干涉图像。Laravel 4上传1图像并保存为多个(3)

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

例如:

1 - 富 - original.jpg

1 - 富 - thumbnail.jpg

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

希望有人能帮助我,谢谢!

回答

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

谢谢。有没有一种方法可以将原始文件放在foreach中? (我也想重新调整原始大小/缩略图相同的方式)。当我试图把它放在foreach中时,我得到了File :: copy()的错误。我怎样才能做到这一点?? – yinshiro

+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(); 
+0

完美,谢谢! – americanknight

相关问题