Search code examples
phplaravelintervention

Save value Base64 to Image PNG use Intervention image Laravel Storage


How can I convert Base64 value to Image PNG using intervention image and laravel storage?

public function userLogout(Request $request) {
  $data = $request->all();
  if ($request->isMethod('post')) {
    $poster = explode(";base64", $request->picture);
    $image_type = explode("image/", $poster[0]);
    $mime_type = '.'.$image_type[1];
    $image_base = base64_decode($poster[1]);

    $data['picture'] = Storage::disk('player-images')->put($image_base, file_get_contents($poster));

    $path = public_path('storage/player-images/'.$image_base);

    Image::make($poster)->save($path);

    $data['picture'] = 'player-images/' . $image_base;
    User::where('name', Auth::user()->name)->update($data);

  }
  return view('gallery');
}

i got an error message:

"file_get_contents() expects parameter 1 to be a valid path, array given"

and here is my ajax function

var canvas = document.getElementById('canvas');
var dataUrl = canvas.toDataURL('image/png');
$(document).ready(function(){
    $('#save').click(function(e){
        e.preventDefault();

        $.ajax({
          headers: {'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')},
          type: "POST",
          url: "/gallery",
          data: {
            picture: dataUrl,
          }
        }).done(function(o) {
            console.log("saved");
        });
    });
});

How can i save the base64 value to database like player-images/blabla.png and store image to path public/storage/player-images/

sorry, my English is bad. thanks.


Solution

  • I solved it!. I changed the function in controller like this.

    public function userLogout(Request $request)
    {
      $data = $request->all();
    
      if ($request->isMethod('post')) {
        if (preg_match('/^data:image\/(\w+);base64,/', $data['picture'])) {
          $value = substr($data['picture'], strpos($data['picture'], ',') + 1);
          $value = base64_decode($value);
          $imageName = time()  . '.png';
          $val = Storage::disk('player-images')->put($imageName, $value);
    
          $path = public_path('storage/player-images/'.$imageName);
          Image::make($data['picture'])->resize(304, 277)->save($path);
    
          $data['picture'] = 'player-images/' . $imageName;
          User::where('name', Auth::user()->name)->update(['picture' => $data['picture']]);
        }
      }
      return view('gallery');
    }