Skip to content
Advertisement

Laravel : Upload 64base image instead of normal

I have an application using React and Laravel where I’m uploading images. I’m using Laravel Image Intervention package.

When testing my API, the upload for a normal image works perfectly.

Using React, the user can select an image from his pc and crop it, then he sees the preview as a generated cropped 64base image.

I would want to upload the generated 64base image to my database instead of a normal one, how to do so ?

Fileupload controller

 public function Store(Request $request)
    {
 $this->validate($request, [
 'filename' => 'image|required|mimes:jpeg,png,jpg,gif,svg'
 ]);
 $originalImage= $request->file('filename');
 $thumbnailImage = Image::make($originalImage);
 
 // Define upload path
 $originalPath = public_path('/images/');
 
 // Save Orginal Image
 $thumbnailImage->save($originalPath.time().$originalImage->getClientOriginalName());
 
 // Save In Database
 $imagemodel= new Photo();
 $imagemodel->photo_name=time().$originalImage->getClientOriginalName();
 $imagemodel->save();
 
 return back()->with('success', 'Image Upload successful');
 
    }

Advertisement

Answer

This one should work

$folderPath = "images/";

$image_parts = explode(";base64,", $request->file('file'));
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '. '.$image_type;

// file_put_contents($file, $image_base64);
Storage::put($file, $image_base64);

Possible alternative:

$image =  Image::make(base64_decode(preg_replace('#^data:image/w+;base64,#i', '', $request->file('file'))))->stream();
Storage::put($file, $image, 'public');
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement