I am developing api in Laravel 5.4. I will receive the image in base64 format. How can I convert the base64 to image in Laravel?
Asked
Active
Viewed 1.8k times
7
-
4Possible duplicate of [Convert Base64 string to an image file?](https://stackoverflow.com/questions/15153776/convert-base64-string-to-an-image-file) – mehulmpt Jan 08 '18 at 15:22
-
Does this answer your question? [How to save a PNG image server-side, from a base64 data string](https://stackoverflow.com/questions/11511511/how-to-save-a-png-image-server-side-from-a-base64-data-string) – miken32 Mar 20 '20 at 15:09
3 Answers
5
this solution will deal with all image types
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'image_' . time() . '.' . $image_extension[1]; //generating unique file name;
Storage::disk('public')->put($imageName,base64_decode($image));

Yehia Salah
- 59
- 1
- 3
-
-
After perform preg_match function $image_extension variable will be containing the image extension – Yehia Salah Aug 30 '18 at 20:05
-
0
I found the solution:
use Illuminate\Support\Facades\Storage;
function createImageFromBase64(Request $request)
{
$file_data = $request->input('image_file');
$file_name = 'image_' . time() . '.png'; //generating unique file name;
if ($file_data != "") { // storing image in storage/app/public Folder
Storage::disk('public')->put($file_name, base64_decode($file_data));
}
}

Simon Shrestha
- 103
- 1
- 1
- 6
-
this does save the file into the folder, but it gets corrupted and not usefull – Agil Jun 21 '18 at 16:46
-
-
do you mean the actual image? if that is what you mean it works pretty well – Agil Jun 21 '18 at 17:00
-
May be the base64 image that you have sent using api is jpg image. The above code saves it .png. So it gets corrupted. So could you first convert png image to base64 and use the above code. – Simon Shrestha Jun 21 '18 at 17:05
-
Lol, I already tried that. I used the same type as it is before upload. and it does not work – Agil Jun 21 '18 at 17:07
-
-
-
I tried this and it doesn't return any data within the image. It's a blank image... – ahinkle Aug 29 '18 at 19:17
0
1- use package intervention image
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManagerStatic;
use Illuminate\Support\Str;
$logo = ImageManagerStatic::make($request->logo)->encode('png');
$logo_name = Str::random(40) . '.png';
Storage::disk('s3')->put('products_seller/' . $logo_name, $logo);

ali hassan
- 321
- 2
- 5