从字符串中提取base64图像并以表单形式发布

时间:2019-04-08 22:32:36

标签: php laravel laravel-blade

我正在尝试在Laravel项目中上传带有表单的图像。我有一个图像裁剪器,将图像另存为data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/..

裁剪程序发送一个JSON字符串,其中包含文件的一个base64编码字符串,我需要将JSON字符串解析为一个对象,然后提取base64字符串并将其转换为文件对象。

我正在使用Image Intervention进行上传过程

控制器功能

public function store(Request $request)

    {

        // save post in db

        $post = new Post;

        $post->title = $request->title;
        $post->body = $request->body;
        $post->user_id = auth()->id();



        if ($request->hasFile('featimage')) {
            $image = $request->file('featimage');
            $filename = time() . '.' . $image->getCLientOriginalExtension();

            $image = trim($image);
            $image = str_replace('data:image/png;base64,', '', $image);
            $image = str_replace('data:image/jpg;base64,', '', $image);
            $image = str_replace('data:image/jpeg;base64,', '', $image);
            $image = str_replace('data:image/gif;base64,', '', $image);
            $image = str_replace(' ', '+', $image);

            $imagedata = base64_decode($image);
            //Set image whole path here 

            $location = public_path('images/uploads/' . $filename);
            Image::make($image)->save($location);
            $post->image = $filename;
        }

        $post->save();

        $post->tags()->sync($request->tags, false);


        Session::flash('success', 'The blog post was saved successfully!');

        return redirect()->route('posts.show', $post->id);

                    }

查看

<form class="form-horizontal" action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">{{ csrf_field() }}

<fieldset class="form-group">
<label for="featimage">Upload Image</label>
<input type="file" class="form-control slim" data-ratio="4:3" name="featimage">

<label class="col-md-2 col-form-label">Post Body</label>
<textarea type="textarea" class="form-control" rows="10" name="body"></textarea>
</fieldset>

<button class="btn btn-primary btn-block" name="submit">Save</button>
<button class="btn btn-danger btn-block" name="submit">Cancel</button>

</form>    

我已经读过其他类似的帖子,但是我显然缺少了一些东西,但是我只是不知道什么。

3 个答案:

答案 0 :(得分:0)

尝试此希望对您有用。

$featimage= $request->featimage; // base64 encoded image string

                    if(!empty($featimage)){
                        $image_parts = explode(";base64,", $featimage);
                        $image_type_aux = explode("image/", $image_parts[0]);
                        $image_type = $image_type_aux[1];
                        $image_base64 = base64_decode($image_parts[1]);
                        $imagename = rand(1,999).time().'.png';
                        $RootPath = public_path("images/uploads/"); // path where you want to upload image
                        if(!File::exists($categoryRootPath)) {
                            File::makeDirectory($categoryRootPath, 0777, true, true);
                        }

                        file_put_contents($RootPath .$imagename,$image_base64);


                        $post->image = $imagename;  
                    }

答案 1 :(得分:0)

我在程序中运行了您的代码,但出现很多错误。如果您尝试将输入作为base-64编码的字符串作为'data:image / jpeg; base64,/ 9j / 4AAQSkZJRgABAQAAAQABAAD / ..'并将其转换为图像文件,则使用以下代码。...

$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = auth()->id();

if ($request->featimage) {
   $image = $request->featimage;  // your base64 encoded
   $filename = time().'.' . explode('/', explode(':', substr($image, 0, strpos($image, ';')))[1])[1];

    $image = str_replace('data:image/jpg;base64,', '', $image);
    $image = str_replace(' ', '+', $image);
    $location = public_path('images/uploads/' . $filename);
    Image::make($image)->save($location);
    $post->image = $filename;
   }
    $post->save();
}

如果您要获取普通的图像文件并将其保存在公共文件夹中,并将其转换为base-64格式,请使用以下代码。

$post = new Post;
$post->title = $request->title;
$post->body = $request->body;
$post->user_id = auth()->id();
if ($request->hasFile('featimage')) {
   $image = $request->file('featimage'); 
   $extension = $image->getCLientOriginalExtension();  //gives extension of image
   $filename = time() . '.' . $extension; //gives filename

   $location = public_path('images/uploads/' . $filename); //sets path

   $image = Image::make($image)->save($location); //makes image and saves it to that location

   $base64 = 'data:image/' . $extension . ';base64,' . base64_encode($image); //changes image to base64 image

   $post->image = $filename;
 }
$post->save();

我希望以下代码为您提供解决方案。 谢谢。

答案 2 :(得分:0)

您可以尝试使用此功能。

    function uploadImage($base_64_string,$image_name)
{

    preg_match("/^data:image\/(.*);base64/i", $base_64_string, $match);
    $extension_array = explode('/', (explode(';', $base_64_string))[0]);
    $extension = end($extension_array);

    $img = $base_64_string;
    if ($extension == 'png' || $extension == 'jpg' || $extension == 'jpeg'){
        $img = str_replace('data:image/' . $extension . ';base64,', '', $img);}
    elseif ($extension == 'mp4' || $extension == 'mov'){
        $img = str_replace('data:video/' . $extension . ';base64,', '', $img);
    }
    $img = str_replace(' ', '+', $img);

    $data = base64_decode($img);

    $fileNameI = $image_name.'_'.rand().time() . '.' . $extension;

//Uploading Image To S3 Bucket
    $s3 = Storage::disk('s3-image');
    $filePath = Config::get('common.Image_Folder') . $fileNameI;
    $s3->put($filePath, $data, 'public');

    return $fileNameI;
}

如果您没有Bucket,则可以将图像存储在本地目录中。