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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22115607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:06:49  来源:igfitidea点击:

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

imageuploadlaravel

提问by yinshiro

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

我正在尝试使用 laravel 4.(使用资源控制器)制作图像上传脚本,并且我正在使用包干预图像。

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

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

for example:

例如:

1-foo-original.jpg

1-foo-original.jpg

1-foo-thumbnail.jpg

1-foo-thumbnail.jpg

1-foo-resized.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!

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

回答by The Alpha

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

回答by user3483754

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