Laravel 5.2: how create image file from json - laravel

In my controller i receive from form data like this:
"output":{"width":500,"height":500,"image":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQFAH/9k=..."},"actions":{"crop":{"x":97,"y":0,"height":500,"width":500},"size":null}}[
Can I create image file from this data?
upd 1.
Decode the json - ok, pull out the image data - ok, decode the base64 - ok, but when I try write to disk then I got error: NotReadableException in Decoder.php line 96: Unable to init from given binary data.
$file = Request::input('photo');
$imagedata=json_decode($file);
$file=$imagedata->output->image;
$image = base64_decode($file);
$png_url = "user-".time().".png";
$path = "/public/".$png_url;
Image::make($image)->save($path);
upd 2.
Solved with file_put_contents function.

here is how you can save image from a json data:
$data = 'iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABl'
. 'BMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDr'
. 'EX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r'
. '8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==';
$data = base64_decode($data);
$im = imagecreatefromstring($data);
if ($im !== false) {
echo imagejpeg($im , base_path() . DIRECTORY_SEPARATOR . "sth.jpeg") ;
}
else {
echo 'An error occurred.';
}

This is working:
$file = Request::input('photo');
$imagedata=json_decode($file);
$file=$imagedata->output->image;
$png_url = "user-".time().".png";
$path = "uploads/".$png_url;
$image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
file_put_contents($path, $image);

Related

How to Save File in storage folder with Original name?

I want to store an uploaded file with its original client name in the storage folder. What do I need to add or change in my code?Any help or recommendation will be greatly appreciated
Here my Controller
public function store(Request $request) {
$path = "dev/table/".$input['id']."";
$originalName = $request->file->getClientOriginalName();
$file = $request->file;
Storage::disk('local')->put($path . '/' . $originalName, $request->file);
}
Edit: I know how to get the originalClientName. the problem is storing the file in the folder using the original name, not the hash name. It doesn't store in the file in the original it makes a new folder instead here is the output "dev/table/101/Capture1.PNG/xtZ9iFoJMoLrLaPDDPvc4DMJEXkRL3R4qWOionMC.png" what I trying to get is "dev/table/101/Capture1.PNG"
I have tried to use StoreAs Or putFileAs but the method is undefined
I managed to figure out how to store it with a custom name, for those who want to know how to do it here is the code
$id = $input['id'];
$originalName = $request->file->getClientOriginalName();
$path = "dev/table/$id/".$originalName;
Storage::disk('local')->put($path, file_get_contents($request->file));
public function store(Request $request) {
$originalName = $request->file->getClientOriginalName();
$extension = $request->file->getClientOriginalExtension();
$path = "dev/table/" . $input['id'] . "/" . $originalName . "." . $extension;
$file = $request->file;
Storage::disk('local')->put($path, $file);
}
To get the original file name you can use this in your ControllerClass:
$file = $request->file->getClientOriginalName();
To get additional the extension you can use this Laravel Request Method:
$ext = $request->file->getClientOriginalExtension();
Then you can save with:
$fileName = $file.'.'.$ext;
$request->file->storeAs($path, $fileName);
// or
Storage::disk('local')->put($path . '/' . $fileName , $request->file);
You can save files using storage with the default name using putFileAs function instead of put which allow take third param as a file name
$path = "dev/table/101/";
$originalName = request()->file->getClientOriginalName();
$image = request()->file;
Storage::disk('local')->putFileAs($path, $image, $originalName);
Update
You can do something like this with put,
Storage::disk('local')->put($path.$originalName, file_get_contents($image));
I tried to manage like this;
$insurance = $request->file('insurance_papers');
$insuranceExtention = $insurance->getClientOriginalExtension();
$path = "public/files/" . $carrier->id . "/insurance_papers." . $insuranceExtention;
Storage::disk('local')->put($path, file_get_contents($insurance));
You can try this, this is work for me
if ($request->hasFile('attachment')) {
$image = $request->file('attachment');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$path = "foldername/".$imageName;
Storage::disk('public')->put($path, file_get_contents($image));
}

i keep getting "function name must be a string" error

I am building a site using laravel, and I got this error when trying to upload an image. I'm a beginner so, can I get some help?
$user = Auth::user();
$user->name = $request('name');
$user->update();
$file = $request->file('image');
$filename = $request->name . '-' . $user->id . '.jpg';
$user->name = $request('name');
$request is variable not func because of $
Because you didn't follow the naming rules in PHP : $request('name') .
I guess you were going to use $request->get('name')
For Uploading image you can use following code, Although I prefer using Intervention Image
//Auth::loginUsingId(1); #You can test your code without a real login
$data = $request->only(['name']);
if (request()->hasFile('image')) {
$file = request()->file('image');
$fileName = md5($file->getClientOriginalName() . time()) . "." . $file->getClientOriginalExtension();
$destinationPath = public_path('/images/'); //// I assume you have a folder named images in public.
$file->move($destinationPath, $fileName);
$data['avatar'] = $destinationPath.$fileName; // I assume you have a field named avatar in users table.
}
return $data; // Try this line for a better understanding then comment it
Auth::user()->update($data);

Upload image and extract filename instead of file path

I am using following code to upload thumbnail in "storage/app/public/websites"
$path = $request->file('thumbnail')->store('public/websites');
It is working fine and upload images to "websites" directory but problem is it returns the actual path e.g. websites/r63mAKN1kil3BIwvwwRevOv93MgWQFme39BwH8ZV.jpeg
i only want to save image name e.g. r63mAKN1kil3BIwvwwRevOv93MgWQFme39BwH8ZV.jpeg in database table.
By default Laravel generates Unique ID for image name. Is there way to return only filename instead of path ?
This is the hash name, so, first I think you need to separate your steps.
$file = $request->file('thumbnail');
$path = $file->store('public/websites');
when you need to add file name you can use $file->hashName();
You can use the basename function
http://php.net/manual/en/function.basename.php
$filename = basename($path);
This is what you need
$extension = $request->image->getClientOriginalExtension();
$image_name = str_replace(' ', '', trim($request->model) . time() . "." . $extension);
and to move the image to your desired folder use:
$image_path = $request->image->move(public_path('images'), $image_name);
$info = pathinfo( $url );
$contents = ( new \GuzzleHttp\Client() )->get( $url, [ 'verify' => true ] )->getBody()->getContents();
$file = str_finish(sys_get_temp_dir(), '/') . $info[ 'basename' ];
\File::put( $file, $contents );
$ext = ( new UploadedFile( $file, $info[ 'basename' ] ) )->guessExtension();

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

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