Laravel base64 image Api - laravel

I am developing API in Laravel. I will receive the image in base64 format. How can I convert the base64 to image in Laravel?
public function profile_image_upload(User $user, Request $request)
{
$request->validate([
'picture' => 'required|image|mimes:jpeg,png,jpg|max:2048',
], []);
if ($user->picture !== null)
Storage::delete($user->picture);
$res_upload = uploadService::store_image($request->file('picture'), config('upload.user_profile_picture_storage_path'));
if ($res_upload)
return $user->update([
'picture' => $res_upload,
]);
return false;

you can create this helper function
in Helper.php ref link https://laravel-news.com/creating-helpers
function base64ImageUpload($path, $file)
{
$image = $file; // your base64 encoded
if (preg_match('/base64/', $file)) {
$imageInfo = explode(";base64,", $image);
$imgExt = str_replace('data:image/', '', $imageInfo[0]);
$image = substr($image, strpos($image, ",") + 1);
$name = \Str::random(40) . '.' . $imgExt;
$filePath = $path . '/' . $name;
\Storage::put($filePath, base64_decode($image));
return $filePath;
} else {
return null;
}
}
then whenever u need to upload u can just call this function like
$imageLocation = base64ImageUpload(config('upload.user_profile_picture_storage_path'),$request->picture);

Related

Unable to save base 64 Image in Laravel 8

I am trying to save base64 image that is coming from the ajax post (blade file). Below is the code that I am using to save the data but it is giving 500 error.
public function add_ref_images_first(Request $request){
$fileName = "";
$end_url = "";
$count = 0;
$folder_name = 'PUBP' . time();
foreach ($request->images as $data){
$image_64 = $data['src']; //your base64 encoded data
$extension = explode('/', explode(':', substr($image_64, 0, strpos($image_64, ';')))[1])[1]; // .jpg .png .pdf
$replace = substr($image_64, 0, strpos($image_64, ',')+1);
//
// // find substring fro replace here eg: data:image/png;base64,
//
$image = str_replace($replace, '', $image_64);
$image = str_replace(' ', '+', $image);
$ref_image_id = 'PUBR'.time().$count++.'.'.$extension;
$fileName = base64_decode($image)->storeAs($folder_name, $ref_image_id , ['disk' => 'my_uploaded_files']);
if($imageName){
$end_url = $end_url.$imageName.',';
}
}
return response()->json(['url' => $end_url, 'id' => '1']);
}
Is there issue with the code?
instead of the line
$fileName = base64_decode($image)->storeAs($folder_name, $ref_image_id , ['disk'
=> 'my_uploaded_files']);
you can do :
use Illuminate\Support\Facades\Storage;
Storage::put($ref_image_id, base64_decode($image), 'local');
because basically you were trying storeAs on a string value, storeAs works on $request->file('nameFromForm')
reference: https://laravel.com/docs/8.x/filesystem
https://laravel.com/docs/8.x/filesystem#specifying-a-file-name

How to save Base64 string as Image in laravel

I have been searching for the past 2 days now trying to get a solution that decodes base64 in all file type extensions(.png or jpg). All I found was a base64 decoder that only allow one type of extensions.
My Controller:
public function updatepicture(Request $request){
$user = User::find($request->id);
if($user == null){
return response()->json(['statusCode'=>'5', 'statusMessage' => "user account doesn't exists", 'data' => []]);
}
$image = $request->avatar; // your base64 encoded
$decoded_file = base64_decode($image); // decode the file
$mime_type = finfo_buffer(finfo_open(), $decoded_file, FILEINFO_MIME_TYPE); // extract mime type
$extension = $this->mime2ext($mime_type); // extract extension from mime type
$image = str_replace('data:image/'.$extension.';base64,', '', $image);
$image = str_replace(' ', '+', $image);
$filename = str::random(10).'.'.$extension;
//$image = $request->file('avatar');
//$filename = time().'.'.$image->getClientOriginalExtension();
$filePath = 'avatars/'.$filename;
$disk = Storage::disk('gcs')->put($filePath, file_get_contents(base64_decode($image)));
$gcs = Storage::disk('gcs');
$url = $gcs->url('avatars'. "/" . $filename);
$user->avatar = $url;
$user->save();
return response()->json(['statusCode'=>'0', 'statusMessage' => 'Successful','data' => $user], 200);
}
/*
to take mime type as a parameter and return the equivalent extension
*/
public function mime2ext($mime){
$all_mimes = '{"png":["image\/png","image\/x-png"],"bmp":["image\/bmp","image\/x-bmp",
"image\/x-bitmap","image\/x-xbitmap","image\/x-win-bitmap","image\/x-windows-bmp",
"image\/ms-bmp","image\/x-ms-bmp","application\/bmp","application\/x-bmp",
"application\/x-win-bitmap"],"gif":["image\/gif"],"jpeg":["image\/jpeg",
"image\/pjpeg"],"xspf":["application\/xspf+xml"],"vlc":["application\/videolan"],
"wmv":["video\/x-ms-wmv","video\/x-ms-asf"],"au":["audio\/x-au"],
"ac3":["audio\/ac3"],"flac":["audio\/x-flac"],"ogg":["audio\/ogg",
"video\/ogg","application\/ogg"],"kmz":["application\/vnd.google-earth.kmz"],
"kml":["application\/vnd.google-earth.kml+xml"],"rtx":["text\/richtext"],
"rtf":["text\/rtf"],"jar":["application\/java-archive","application\/x-java-application",
"application\/x-jar"],"zip":["application\/x-zip","application\/zip",
"application\/x-zip-compressed","application\/s-compressed","multipart\/x-zip"],
"7zip":["application\/x-compressed"],"xml":["application\/xml","text\/xml"],
"svg":["image\/svg+xml"],"3g2":["video\/3gpp2"],"3gp":["video\/3gp","video\/3gpp"],
"mp4":["video\/mp4"],"m4a":["audio\/x-m4a"],"f4v":["video\/x-f4v"],"flv":["video\/x-flv"],
"webm":["video\/webm"],"aac":["audio\/x-acc"],"m4u":["application\/vnd.mpegurl"],
"pdf":["application\/pdf","application\/octet-stream"],
"pptx":["application\/vnd.openxmlformats-officedocument.presentationml.presentation"],
"ppt":["application\/powerpoint","application\/vnd.ms-powerpoint","application\/vnd.ms-office",
"application\/msword"],"docx":["application\/vnd.openxmlformats-officedocument.wordprocessingml.document"],
"xlsx":["application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application\/vnd.ms-excel"],
"xl":["application\/excel"],"xls":["application\/msexcel","application\/x-msexcel","application\/x-ms-excel",
"application\/x-excel","application\/x-dos_ms_excel","application\/xls","application\/x-xls"],
"xsl":["text\/xsl"],"mpeg":["video\/mpeg"],"mov":["video\/quicktime"],"avi":["video\/x-msvideo",
"video\/msvideo","video\/avi","application\/x-troff-msvideo"],"movie":["video\/x-sgi-movie"],
"log":["text\/x-log"],"txt":["text\/plain"],"css":["text\/css"],"html":["text\/html"],
"wav":["audio\/x-wav","audio\/wave","audio\/wav"],"xhtml":["application\/xhtml+xml"],
"tar":["application\/x-tar"],"tgz":["application\/x-gzip-compressed"],"psd":["application\/x-photoshop",
"image\/vnd.adobe.photoshop"],"exe":["application\/x-msdownload"],"js":["application\/x-javascript"],
"mp3":["audio\/mpeg","audio\/mpg","audio\/mpeg3","audio\/mp3"],"rar":["application\/x-rar","application\/rar",
"application\/x-rar-compressed"],"gzip":["application\/x-gzip"],"hqx":["application\/mac-binhex40",
"application\/mac-binhex","application\/x-binhex40","application\/x-mac-binhex40"],
"cpt":["application\/mac-compactpro"],"bin":["application\/macbinary","application\/mac-binary",
"application\/x-binary","application\/x-macbinary"],"oda":["application\/oda"],
"ai":["application\/postscript"],"smil":["application\/smil"],"mif":["application\/vnd.mif"],
"wbxml":["application\/wbxml"],"wmlc":["application\/wmlc"],"dcr":["application\/x-director"],
"dvi":["application\/x-dvi"],"gtar":["application\/x-gtar"],"php":["application\/x-httpd-php",
"application\/php","application\/x-php","text\/php","text\/x-php","application\/x-httpd-php-source"],
"swf":["application\/x-shockwave-flash"],"sit":["application\/x-stuffit"],"z":["application\/x-compress"],
"mid":["audio\/midi"],"aif":["audio\/x-aiff","audio\/aiff"],"ram":["audio\/x-pn-realaudio"],
"rpm":["audio\/x-pn-realaudio-plugin"],"ra":["audio\/x-realaudio"],"rv":["video\/vnd.rn-realvideo"],
"jp2":["image\/jp2","video\/mj2","image\/jpx","image\/jpm"],"tiff":["image\/tiff"],
"eml":["message\/rfc822"],"pem":["application\/x-x509-user-cert","application\/x-pem-file"],
"p10":["application\/x-pkcs10","application\/pkcs10"],"p12":["application\/x-pkcs12"],
"p7a":["application\/x-pkcs7-signature"],"p7c":["application\/pkcs7-mime","application\/x-pkcs7-mime"],"p7r":["application\/x-pkcs7-certreqresp"],"p7s":["application\/pkcs7-signature"],"crt":["application\/x-x509-ca-cert","application\/pkix-cert"],"crl":["application\/pkix-crl","application\/pkcs-crl"],"pgp":["application\/pgp"],"gpg":["application\/gpg-keys"],"rsa":["application\/x-pkcs7"],"ics":["text\/calendar"],"zsh":["text\/x-scriptzsh"],"cdr":["application\/cdr","application\/coreldraw","application\/x-cdr","application\/x-coreldraw","image\/cdr","image\/x-cdr","zz-application\/zz-winassoc-cdr"],"wma":["audio\/x-ms-wma"],"vcf":["text\/x-vcard"],"srt":["text\/srt"],"vtt":["text\/vtt"],"ico":["image\/x-icon","image\/x-ico","image\/vnd.microsoft.icon"],"csv":["text\/x-comma-separated-values","text\/comma-separated-values","application\/vnd.msexcel"],"json":["application\/json","text\/json"]}';
$all_mimes = json_decode($all_mimes,true);
foreach ($all_mimes as $key => $value) {
if(array_search($mime,$value) !== false) return $key;
}
return false;
}
Please help me align this piece of code, the error massage m getting is as follow:
ErrorException: file_get_contents() expects parameter 1 to be a valid path, string given in file
You don't need to use file_get_contents() function while using put method because you are already converting string to image using base64_decode method.
$disk = Storage::disk('gcs')->put($filePath, base64_decode($image));
Please try like this. It should work.

How to convert base64 images to Url images when using summer note text editor in Laravel inside controller?

I am trying to use image url instead of base64. i kindof figured a way how to get images out of the editor and save it inside the directory, but i am trying to insert it into database. i get this error.
Object of class DOMElement could not be converted to string
below i have added the store function inside my controller
public function store(Request $request)
{
//
$data = $request->all();
if (!$request->has('published')) {
$data['published'] = 0;
} else {
$data['published'] = 1;
}
if (!$request->has('featured')) {
$data['featured'] = 0;
} else {
$data['featured'] = 1;
}
$img = null;
if ($request->hasfile('title_img')) {
$image = $request->file('title_img');
$name = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/blogs/', $name);
$img = '/uploads/blogs/' . $name;
}
/* summernote */
$detail=$data['description'];
$dom = new \DomDocument();
$dom->loadHtml($detail, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$images = $dom->getElementsByTagName('img');
foreach($images as $k => $img){
$data = $img->getAttribute('src');
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$image_name= "/uploads/summernote/" . time().$k.'.jpeg';
$path = public_path() . $image_name;
file_put_contents($path, $data);
$img->removeAttribute('src');
$img->setAttribute('src', $image_name);
}
$detail = $dom->saveHTML();
/* summernote */
$data['title_img'] = $img;
$data['user_id'] = auth()->user()->id;
$title = $data['title'];
$data['slug'] = Str::slug($title);
auth()->user()->posts()->create($data);
return Redirect::route('admin.blog.index')->withSuccess('Whoopie!! New Blog Added!');
}
I hope i can get some help regarding this. Thanks in advance

Laravel upload gifs

i am uploading gif for my posts in laravel but gif is like an image its not moving or something like this
<?php
if($request->hasFile('gif')){
$gif = $request->file('gif');
$gif_filename = time() . '.' . $gif->getClientOriginalName();
$gif_location = public_path('/images/' . $gif_filename);
Image::make($gif)->save($gif_location);
}
$post->gif = $gif_filename;
$post->save();
?>
here is the code what I am using I think everything is kinda correct
I use this method
if(Input::hasFile('imagen')) {
$time = Carbon::now()->format('Y-m-d');
$image = $request->file('imagen');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = $time."-".$name;
$image->move(storage_path(),$fileName);
}
Please try this and let me know how it works :)
An easy way to update and save is to do it like this:
public function store(Request $request)
{
$imgLocation = Storage::disk('public')->put(time() . '.' . $request->file('image')->getClientOriginalName(), $request->gif), $request->file('gif'));
// This would save it to the gifs table if you need something like it, otherwise skip this creation
$gif= Gif::create([
'name' => $request->name,
'path' => $imgLocation
]);
if ($gif) {
return response()->json("Success!");
}
return response()->json("Error!"); // or you return redirect()...
}
$image = $request->file('image');
if(isset($image)) {
if($image->getClientOriginalExtension()=='gif'){
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
$name = $image->getClientOriginalName();
$fileName = 'exerciseimages'."-".$name;
$image->move('storage/courseimages/',$fileName);
}
else{
$fileName = 'exerciseimages'.'-'.uniqid().'.'.$image->getClientOriginalExtension();
if(!Storage::disk('public')->exists('courseimages')){
Storage::disk('public')->makeDirectory('courseimages');
}
$amenitiesimg = Image::make($image)->resize(250,250)->stream();
Storage::disk('public')->put('courseimages/'.$fileName, $amenitiesimg);
}
}
else {
$fileName = 'default.png';
}

Laravel 5 - Image Upload and Resize using Intervention Image Package

I want to upload a photo with some posts.
This is my controller
public function store(WisataRequest $request)
{
$input = $request->all();
if ($request->hasFile('gambar')) {
$gambar = $request->file('gambar');
$filename = time() . '.' . $gambar->getClientOriginalExtension();
if ($request->file('gambar')->isValid()) {
Image::make($gambar)->resize(300, 300)->save(public_path('/upload/gambar/'.$filename));
$input->gambar = $filename;
$input->save();
}
}
$wisata = Wisata::create($input);
Session::flash('flash_message', 'Berhasil Terkirim');
return redirect('admin_wisata');
}
But when it runs i found an error
Attempt to assign property of non-object
Change
$input->gambar = $filename;
$input->save();
To
$input['gambar']= $filename;
$input variable is not an object, it is an array. You can try accessing gambar in $input by doing $input['gambar']
You can put
$input['gambar']= $filename;
Instead of
$input->gambar = $filename;
$input->save();
OR
public function store(WisataRequest $request)
{
$wista = new Wista;
$wist->name = $request->name;
-----
$wista->save();
if ($request->hasFile('gambar')) {
$gambar = $request->file('gambar');
$filename = time() . '.' . $gambar->getClientOriginalExtension();
if ($request->file('gambar')->isValid()) {
Image::make($gambar)->resize(300, 300)->save(public_path('/upload/gambar/'.$filename));
$wista->gambar = $filename;
$wista->save();
}
}
Session::flash('flash_message', 'Berhasil Terkirim');
return redirect('admin_wisata');
}

Resources