How to convert base64 to image in Laravel 5.4? - laravel

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?

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

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

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

Related

Resize image and store it to s3

Default image upload process in my app like this.
Get image from request and store it to s3 and a local variable.
$path = $request->file("image")->store("images", "s3");
After this I make it public.
Storage::disk("s3")->setVisibility($path, 'public');
And store to DB like this.
$variable = ModelName::create([
"image" => basename($path),
"image_url" => Storage::disk("s3")->url($path),
But how to resize the image before store it to s3?
I try to write like this
$extension = $request->file('image')->getClientOriginalExtension();
$normal = Image::make($request->file('image'))->resize(160, 160)->encode($extension);
$filename = md5(time()).'_'.$request->file('image')->getClientOriginalName();
$img = Storage::disk('s3')->put('/images/'.$filename, (string)$normal, 'public');
And then
"image" => basename($filename ),
"image_url" => Storage::disk("s3")->url($img),
This works except one thing. I can't get URL (to store DB) for uploaded image.
How to get correct public url for uploaded image?
Note:I use Intervention Image package
Storage::put() would only return the path if it's an instance of File or UploadedFile (source). In this case $normal isn't, so put() would return a boolean instead. Also, using getClientOriginalExtension() probably isn't a good idea since it's not considered a safe value (source).
So here's a bit improved version:
$filename = $request->file('file')->hashname();
$image = Image::make($request->file('file'))->resize(160, 160);
Storage::disk('s3')->put('/images/'.$filename, $image->stream(), 'public');
$url = Storage::disk('s3')->url('/images/'.$filename);
You can now save $url and $filename into your db.
You can try my code snippet.
$file = $request->file('image');
$fileName = md5(time()).'.'.$file->getClientOriginalExtension();
/** #var Intervention $image */
$image = Image::make($file);
if ($image->width() > ($maxWidth ?? 500)) {
$image = $image->resize(500, null, function ($constraint) {$constraint->aspectRatio();});
}
$image = $image->stream();
try {
/** #var Storage $path */
Storage::disk('s3')->put(
$dir . DIRECTORY_SEPARATOR . $fileName, $image->__toString()
);
} catch (\Exception $exception) {
Log::debug($exception->getMessage());
}

Image not saving in Database in Laravel

I am trying to store image into database after it has been converted to base64 and also decoded. The image stores inside the Storage path but does not save into mysql database.
What am i doing wrong?
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$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 = 'profile' . time() . '.' . $image_extension[1]; //generating unique file name;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->all());
}
Try this:
$user = auth('api')->user();
if ($request['image']) {
$data = $request['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$image = base64_decode($data);
$photoName = 'profile' . time() . '.' . $image_extension[1];
$request['image'] = $photoName;
Storage::disk('public')->put($photoName, $image);
$user->update($request->all());
}
I had to do this
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$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 = 'profile' . time() . '.' . $image_extension[1]; //generating unique file name;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
}
and it worked
I recommend you to use uploader packages like:
https://github.com/spatie/laravel-medialibrary
or
https://github.com/alaaelgndy/FileUploader
to help you in media management without writing all these lines of code in every place you want to upload files.
enjoy them.

Laravel deploy: storage image doesn't work correctly

After deploying my laravel project from local to Apache web server, all works correctly except images link. Here the code:
Images are stored in:
storage/app/public/photos
after i've run command:
php artisan storage:link
Images are linked at:
public/storage/photos
Controller:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photo = $file->storeAs('public/photos', 'foto-' . time() . '.' . $extension);
$user->photo = $photo;
$user->save();
}
Images are uploaded correctly on storage/app/public/photos and correctly linked in public/storage/photos but it doesn't display on frontend.
in blade, i've tried to use Storage::url to retrieve the path
{{Storage::url($user->photo)}}
and asset()
{{asset($user->photo)}}
in both cases, image doesn't exist
The public path of image is:
http://mywebsite.com/storage/photos/foto-1522914164.png
You should Use url function to show your image like below way.
url($user->photo);
I'd suggest to change the controller code as follows:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'foto-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$user->photo = 'photos/' . $photoFileName;
$user->save();
}
Then you can use {{asset($user->photo)}} in your blade.
on my webspace, it seems that the only way to display image correctly is to create a custom route that read and serve the image.
i'm solved like this:
i'm storing only image name in db:
if ($request->hasFile('photo')) {
$extension = $request->file('photo')->getClientOriginalExtension();
$file = $request->file('photo');
$photoFileName = 'photo-' . $model->id . '.-' . time() . '.' . $extension;
$photo = $file->storeAs('public/photos', $photoFileName);
$store = $photoFileName;
}
then, i've create custom route that read images and display them:
Route::get('storage/{filename}.{ext}', function ($filename, $ext) {
$folders = glob(storage_path('app/public/*'), GLOB_ONLYDIR);
$path = '';
foreach ($folders as $folder) {
$path = $folder . '/' . $filename . '.' . $ext;
if (File::exists($path)) {
break;
}
}
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header('Content-Type', $type);
return $response;
});
in blade, i'm using Storage to display image:
{{ Storage::url($photo->photo) }}}

Laravel 5 image resize

I use Laravel 5 and have a form to upload a image. When saving the file I have in my controller methods to get the image and put it in a directory:
if ($request->hasFile('picture')) {
$destinationPath = 'uploads';
$filename = $image->getClientOriginalName();
$extension = $image->getClientOriginalExtension(); // add
$picture = sha1($filename . time()) . '.' . $extension; //add
$offer->image = $picture;
$image->move($destinationPath, $picture);
}
$offer->save();
Before I save the file I would like to resize the file with a max. width of 800px. Is there a image resize or compression function in Laravel available?
What would be the best idea to do this?
You can install and use package, similar to intervention.
Example from official website:
$img = Image::make('public/foo.jpg');
$img->resize(320, 240);
$img->insert('public/watermark.png');
$img->save('public/bar.jpg');
Image::make($request->file('image'))->resize(462, 462)->save('upload_path/filename.jpg'));
try this code

How to save a jpeg image from a base64 data string with move_uploaded_file or file_put_contents?

currently i developing a mobile app that able to snap photo and save in server. I able to pass the image base64 data string to my php using AJAX. I also can decode the base64 data string to image, but cannot save in my server. Every time i run my app, the result show that i already save my image into server but when i check in my server i didn't find it. I follow the example on https://xuri.me/2014/11/18/save-a-png-image-from-a-base64-data-string-with-php.html.
Below is my php code.
$img = $_POST['img'];
$img = str_replace('data:image/jpg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$img_name = uniqid();
$file_name = $img_name . '.jpeg';
$file_path = realpath("../media/rewardreceipt/");
$file_path = $file_path . "/" . $file_name ;
if(file_put_contents($file_path , $data)) {
$arr = array('result' =>$file_name);
echo json_encode($arr);
} else{
$arr = array('result' =>'false');
echo json_encode($arr);
}

Resources