laravel livewire intervention images - laravel

I am trying to use Intervention image with Livewire to reduce the sizes and I am not succeeding. They can guide me or tell me if Livewire may not allow it.
I am trying to pass this methodology:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
to this other way:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
Image::make($pathGaleria)->resize(1200, null, function ($constraint) {
$constraint->aspectRatio();
})
->save($imgUrl);
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
}
but the page remains blank. Thank you.

I found this today, may work for you
https://gist.github.com/daugaard47/659984245d31b895d00ee5dcbdee44ec
+
$images = Collection::wrap($request->file('file'));
$images->each(function ($image) use ($id) {
$basename = Str::random();
$original = $basename . '.' . $image->getClientOriginalExtension();
$thumbnail = $basename . '_thumb.' . $image->getClientOriginalExtension();
ImageManager::make($image)
->fit(250, 250)
->save(public_path('/images/' . $thumbnail));
$image->move(public_path('/images/'), $original);
Model::create([
]);
});

Related

image not store in database laravel

I want to Create app in laravel that manage my events
i use this code for EventController
public function store(Request $request)
{
$request->validate([
'inviter'=>'max:255',
'date'=>'max:255',
'phone'=>'max:255',
'whatsapp'=>'max:255',
'location'=>'max:255',
'approval'=>'max:255',
'number'=>'max:255',
'description'=>'max:255',
'track'=>'max:255',
]);
$eve = new Event([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);
if ($request->hasFile('file')) {
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$filePath = time() . '.' . $file->getClientOriginalName();
$request->file->move(public_path('uploads/events'), $filePath);
$eventImage = Image::createNew();
$eventImage->filename_path = $filePath;
$eventImage->original_filename = $fileName;
$eventImage->event_id = $eve->id;
$eventImage->save();
}
return redirect(route('event.index'))->with('success','Event Created');
}
but image dont create I think related to event_id when I was testing the code correctly and incorrectly
Try this
$eve = Event::create([
'inviter'=> $request->get('inviter'),
'date'=> $request->get('date'),
'phone'=> $request->get('phone'),
'whatsapp'=> $request->get('whatsapp'),
'location'=> $request->get('location'),
'number'=> $request->get('number'),
'approval'=> $request->get('approval'),
'description'=> $request->get('description'),
'track'=> $request->get('track'),
]);

Sending an image with HTTP POST

Recently I wanted to separate my project in different services to I wanted to make blogs independent from the project.
In the first project i have written this code. I want to send the data that i get from the form to another API http://127.0.0.1:100/api/saveBlog
public function update(Request $request, $blog)
{
if (!$blog instanceof Blog) {
$blog = $this->getById($blog);
}
$response = Http::post("http://127.0.0.1:100/api/saveBlog",[
'name' => $request->input('name'),
'description' => $request->input('description'),
'name' => $request->input('name'),
'photto' => $request->file('photto')
]);
dd($response->status());
}
In the API service i am trying to read the data
Route::post("/saveBlog",function (Request $request){
$blog = new Blog();
$blog->name = $request->input('name');
$blog->description = $request->input('description');
$blog->name = $request->input('name');
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
return $blog->save();
});
But i am getting 500 status error and blog is not being saved in database.
I think the problem is with $request->file('photto')
ANY IDEA?
check whether image exist in request like below
if($request->has('photto')){
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
}
Updates
$photo = fopen(public_path('/storage/filename'), 'r');
$response = Http::
attach('photo', $photo)
->post($url, [
'param_1' => 'param_1 contents',
...
]);

Laravel I try to duplicate an object and add pictures in each object

I have a room to add. And there are fields called pieces. If the user has written all the fields, he chose pictures for the room. and wrote 5 pieces. I want to add 5 pieces to the same room with selected fields and photos. That is, duplicate the same object in several pieces.
RoomController store function
public function store(Request $request)
{
$request->validate([
'title.*' => 'required',
'content.*' => 'required',
'people' => 'required',
'hotel_id' => 'required',
'night_price' => 'required',
'pieces' => 'required',
'single_bed' => 'required',
'double_bed' => 'required',
'roomImages' => 'required',
'roomImages.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$rooms = array_fill(1, $request->get('pieces'), $request->all());
foreach ($rooms as $room){
dd($rooms);
$obj = new Room();
// Set translations
$obj->setTranslations('title', $room['title']);
$obj->setTranslations('content', $room['content']);
// Save object
$obj->amenities = $room['amenities'];
$obj->fill($room);
$obj->save();
foreach ($room['roomImages'] as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
// Save image in Model Image
$file = new Image();
$file->src = $file_name;
$obj->file()->save($file);
}
}
return redirect()->route('rooms.index');
}
Error
One circle of the foreach is running, the object with the pictures is added. On the 2nd lap, the foreach stops and shows this error
Try the bellow code
foreach ($request->roomImages as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
}
$rooms = array_fill(1, $request->get('pieces'), $request->all());
foreach ($rooms as $key => $room){
$obj = new Room();
// Set translations
$obj->setTranslations('title', $room['title']);
$obj->setTranslations('content', $room['content']);
// Save object
$obj->amenities = $room['amenities'];
$obj->fill($room);
$obj->save();
\File::copy(public_path('/uploads/rooms/'.$file_name), public_path('/uploads/rooms/'.$key.$file_name));
$file = new Image();
$file->src = $key.$file_name;
$obj->file()->save($file);
}
\File::delete(public_path('/uploads/rooms/'.$file_name));
The move function will delete the file from the original request. So when the loop run second time, you are getting error.
So your issue looks like you are overriding $file when creating your Image model.
foreach ($room['roomImages'] as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
// Save image in Model Image
// Updated variable name
$image = new Image();
$image->src = $file_name;
// save Model
$image->save();
$obj->file()->save($file);
}

How to delete old picture after new one uploaded

I have this in my Controller which handles image upload
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];
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
}
How can i delete the old picture from the directory after new one has been uploaded.
You can delete the image with Storage::delete() method (https://laravel.com/docs/7.x/filesystem#deleting-files). So, get the image before you update, then delete when it's ok to do:
$oldImage = $user->profilePicture;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
Storage::disk('public')->delete($oldImage);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
PS: I'm not sure if the profilePicture attribute is the same of your storage. Anyway, make any adjustment to match if needed.

Resize to 3 different size at a time to different path using intervention in laravel 5.0

I am trying to resize images in Laravel 4.2 using intervention, but i want to move images to 2 different folders at a time.
If i run the below code
if(Input::hasFile('product_images')) {
$images = Input::file('product_images');
foreach($images as $image) {
if($image->isValid()) {
$file_name = microtime();
$file_name = str_replace(' ', '_', $file_name);
$file_name = str_replace('.', '_', $file_name);
$file_name = $file_name . '.' . $image->getClientOriginalExtension();
$file_name = $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/', $file_name);
$file = Image::make(sprintf('uploads/%s', $file_name))->resize(800, 600)->save();
It(above code) runs proper for uploads folder but, if i create another folder called thumbnail inside uploads & add below line i'll get error as....,
("Intervention\Image\Exception\NotReadableException","message":"Image source not readable")........
$file = Image::make(sprintf('uploads/thumbnail/%s', $file_name))->resize(75,75)->save();
Thanks in advance
The issue with the above code is original file being resized to a blurry images. It can be avoided by using aspectRatio as used in the below code.
Also set memory limit to -1. So that it'll be easier to upload a larger images for a Web page, 30 to 60 KB and larger.
Implementation will be much like:
$imageType = array(
'thumbnail' => array(
'width' => 50,
'height' => 50
),
'detail_page' => array(
'width' => 200,
'height' => 200
),
'product' => array(
'width' => 400,
'height' => 400
),
);
if(Request::hasFile('image')) {
$image = Request::file('image');
if($image->isValid()) {
ini_set('memory_limit', '-1');
$file_name = microtime();
$file_name = str_replace(' ', '_', $file_name);
$file_name = str_replace('.', '_', $file_name);
$file_name = $file_name . '.' . $image->getClientOriginalExtension();
$image->move(public_path() . '/uploads/', $file_name);
$response['file_name'] = $file_name;
foreach ($imageType as $key => $value) {
$file = Image::make(sprintf('uploads/%s', $file_name))->resize($value['width'], $value['height'],
function($constraint) {
$constraint->aspectRatio();
});
$file->save(public_path() . '/uploads/'.$value['width'].'X'.$value['height'].'/'. $file_name);
}
$product_image_url = URL::to('uploads/' . $file_name);
I finally managed to resize images in Laravel 4.2 using intervention, also to move images to different folders at a time in one line of code.
See the code snippet below,
$file = Image::make(sprintf('uploads/%s', $file_name))
->resize(800, 600)->save()
->resize('1280', '1024')->save(public_path() . '/uploads/1280x1024/' . $file_name)
->resize('316', '255')->save(public_path() . '/uploads/316x255/' . $file_name)
->resize('118', '95')->save(public_path() . '/uploads/118x95/' . $file_name);
As you can see, I have created 3 folders named 1280x1024, 316x255, 118x95 in uploads folder in public_path.
So if you use above code, after resize() give the path to save() function and keep on repeating to save all resized images at a time.
If anyone knows even better answers, please try to post it and improve it.
Use the intervention/image package
public function upload() {
$image = \Image::make(\Input::file('image'));
$path = storage_path('app')."/";
// encode image to png
$image->encode('png');
// save original
$image->save($path."original.png");
//resize
$image->resize(300,200);
// save resized
$image->save($path."resized.png");
}
if(Input::file()){
$image = Input::file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('profilepics/' . $filename);
Image::make($image->getRealPath())->resize(200, 200)->save($path);
$user->image = $filename;
$user->save();
}

Resources