how to save base64 image decode to public folder in laravel - php

I get an image with format String base64 and i want to decode that string to be an image and save it to public folder in laravel.
This is my controller:
//decode string base64 image to image
$image = base64_decode($request->input('ttd'));
//create image name
$photo_name = time().'.png';
$destinationPath = public_path('/uploads');
//save image to folder
$image->move($destinationPath, $photo_name);
$img_url = asset('/uploads'.$photo_name);
$data = new Transaction();
$data->transaction_id = $request->input('fa_transaction_id');
$data->user_id = $request->input('userid');
$data->photo_name = $photo_name;
$data->photo_url = $img_url;
$data->save();
when i'm trying echo $image, i got the decode value, and also for $photo_name i got the value too, but when the function running i got this error
Call to a member function move() on string
how to fix this error?

//Controller
use Illuminate\Support\Facades\Storage;
//Inside method
$image = $request->image; // your base64 encoded
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
$imageName = str_random(10) . '.png';
Storage::disk('local')->put($imageName, base64_decode($image));
Also, make sure that your local disk is configured like that in /config/filesystems.php
'local' => [
'driver' => 'local',
'root' => storage_path('app/public'),
]
With that, file will be saved in /storage/app/public directory.
Don't forget to write php artisan storage:link to make files from that directory available in /public directory, so users will can retrieve them.

Saving image in database not a recommanded way to store image in db, reason is speed increase of memory, The correct way is just save the link to it.
Anyway, you can save your image in base64 with these line of code.
Get the correct image from path in your server not from link in the $path.
<?php
// Base 64 transform image
$path = __DIR__ .'/myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo $base64;

Related

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');
}
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');

Lumen get public directory

I want to store an image file with response like
http://localhost/storage/image/someimage.jpg
But when tried to use storage_path it returned
/home/../../../someimage.jpg
here's what i tried
if ($request->hasFile('avatar_image')) {
$image = $request->file('avatar_image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = storage_path('images');
$image->move($destinationPath, $name);
$detail->update([
'avatar_image' => env('APP_URL').$destinationPath.'/'.$name
]);
}
Is there any way to get only the storage directory like /storage/image/...
so i can concat it with my app_url
so what i did was symlink my storage/images with public folder then put it like
if ($request->hasFile('avatar_image')) {
$image = $request->file('avatar_image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = storage_path('images');
$image->move($destinationPath, $name);
$file_path = env('APP_URL').'/public/images'.$name;
$detail->update([
'avatar_image' => $file_path
]);
}
it did works but dont know if its good enough

How can I convert base64 string to image and upload the file in storage and save the path in the database

I am building an SPA. I am getting base64 string from my vue component in my laravel controller. How can I convert base64 string to a file. Then upload the site into my laravel local storage and then save the path in the database table ?
I have googled almost every link and tried too many things. I even tried image intervention but the only thing I was able to achieve was to upload the file into the laravel storage but wasn't able to store the right path in the database table.
Here is my controller code
$team = new Team;
$team->hood_id = $user->hood->id;
$team->title = $request->title;
$team->max_no_of_players = $request->max_no_of_players;
$team->description = $request->description;
$team->about_us = $request->about_us;
$team->email = $request->email;
$team->contact_no = $request->contact_no;
$team->meetup_place = $request->meetup_place;
/**
* Image base64 converting code starts from here
*/
$image = $request->image;
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;
$team->image = Storage::disk('public')->put($imageName, base64_decode($image));
I should be able to use Storage::url($image); when fetching the teams from database table. But right now I am not getting the correct path, Any help would be highly appreciated
In this way, you can fetch the file from the Base64 URL, I used this way.
$pos = strpos($fileBase64Url, ';');
$filetype = explode('/', substr($fileBase64Url, 0, $pos))[1]; //get file type
$contents = file_get_contents($fileBase64Url); //get the content from the URL
$unique_name = 'filename.' . $filetype; //file name
Storage::put('/public/folderName/' . $unique_name, $contents); //save to the directory
//$unique_name (Save this name to the Database)
And this is the path of this image file
http://127.0.0.1:8000/storage/folderName/filename.jpg (remove public form url)

How to store image path in database - using laravel

currently i can store file name is database and in public folder of laravel but i want to store file path in database?
My Controller:
$image=$userProfile['image'];
$image1 = base64_decode($image);
$filename = time().'.'.$extension;
Storage::disk('public')->put($filename,$image1);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $filename]);
How i can store image path in laravel and image name in public folder? i am sending image in json using base64.
Your help will be highly appreciated?
Use:
$image = $userProfile['image'];
$image1 = base64_decode($image);
$filename = time().'.'.$extension;
Storage::disk('public')->put($filename,$image1);
$filePath = Storage::disk('public')->getAdapter()->getPathPrefix();
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $filePath.$filename]);
First type this command :
php artisan storage:link
it will create a symlink to public folder.
in your controller, you can write like this :
if ($request->file('image')) {
$file = $request->file('image')->store('images', 'public');
$new_product->image = $file;
}
this code will insert a random string included the path, so you can have something like this on your image column value 'images/shgsqwerfsd.jpg'

get the file name from base64_decode image

Image will send from mobile api with base64 type and I am trying to get the image name from base64_decoded image file.how can I get it?
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
here is my fuction trying to get image name written with laravel
public function completeProfile($session_id,$username,$fullname,$position,$image){
$user = JWTAuth::toUser($session_id);
$userid = $user->id;
$img = base64_decode($image);
if(file_put_contents(public_path().'/images/users',$img)){
$result = $this->repository->completeProfile($userid,$username,$fullname,$position,$image);
}
return false;
}
I have used this code in slim php framwork to save image to desired folder
$img= base64_decode($val_pic);
$image_name= "test.jpg"; /* name image*/
if( $file = fopen("folder/".$image_name, 'wb')){
fwrite($file, $img);
fclose($file);
}
It is not possible to get the filename from base64 format, as this only contains the data that makes up the image, not it's metadata.

Categories