Good evening, I would like to add the resize function of the images when an image is uploaded on my site, I have installed the necessary dependencies and I have included in the config/app files the provider and the aliases. But I find this error:
production.ERROR: Method Illuminate\Http\UploadedFile::resize does not exist.
I put the part of the code below:
public function imageProfile(Request $request)
{
$user = Auth::user();
$rules = array(
'profile-image' => 'required|image|mimes:jpeg,png,jpg,gif|max:8192|dimensions:min_width=160,min_height=160',
);
$customMessages = [
'profile-image.required' => 'E\' richiesta una immagine per cambiare immagine di profilo.',
'profile-image.image' => 'Devi inserire un immagine valida.',
'profile-image.mimes' => 'L\'immagine inserita non ha un formato adatto.',
'profile-image.dimensions' => 'L\'immagine deve essere minimo 160x160.',
];
$validator = Validator::make(Input::all(), $rules, $customMessages);
if ($validator->fails()) {
return response()->json(['success' => false, 'error' => $this->validationErrorsToString($validator->errors())]);
}
if ($request->hasFile('profile-image')) {
$number = mt_rand(1,1000000);
$image = $request->file('profile-image');
$name = $user->username.'-'.Carbon::now()->toDateString().'-'.$number.'.'.$image->getClientOriginalExtension();
$destinationPath = 'uploads/profile';
$imagePath = $destinationPath. "/". $name;
$image->move($destinationPath, $name);
$image->resize(200,200);
$user->image_profile = $imagePath;
$user->save();
$html = $imagePath;
return response()->json(['success' => true, 'html' => $html, 'image' => $imagePath]);
}
}
Thanks for help me, and have a good day
Laravel does not have a default resize of image. But most laravel developers use 'Image intervention' in handling the image. (Easy to use)
To install (Image intervention):
STEP 1 Run
composer require intervention/image
STEP 2 On your config/app.php:
In the $providers array, add the following:
Intervention\Image\ImageServiceProvider::class
In the $aliases array,add the following:
'Image' => Intervention\Image\Facades\Image::class
If you have problems your GD librabry is missing, intall it
PHP5: sudo apt-get install php5-gd
PHP7: sudo apt-get install php7.0-gd
~~ To use on your controller ~~
STEP 3 On top of your controller
use Intervention\Image\ImageManagerStatic as Image;
STEP 4 On your method (there are several ways but this will give you an idea)
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300, 300);
$image_resize->save(public_path('images/ServiceImages/' .$filename));
}
Related
I'm trying to reduce the size of the images uploaded by users on a project I'm working on. The main idea is to resize the image down by 10%, and checking if its size is under a set requirement.
Here is my code: ($optimisedImage is the original image uploaded by the user and recieved from the request)
$optimisedImage->save("user_uploads/" . $scrollFeedName);
$scrollFeedImg = Image::make("user_uploads/" . $scrollFeedName);
while(filesize("user_uploads/" . $scrollFeedName) > 1000000) {
$scrollFeedImg->resize(floor($scrollFeedImg->width() * 0.9), floor($scrollFeedImg->height() * 0.9));
$scrollFeedImg->save();
}
Currently there seems to be an issue with the loop, getting stuck. I also tried the Intervention Image filesize(), but was getting an error stating that the width or heigth need to be higher than 0.
Is there any way to achieve my goal, or are there better solutions to that problem?
Stack:
PHP: 8.1.10
Laravel: 9.19
Step 1: Install intervention for resize image
composer require intervention/image
Step 2: Add provider path and alias path in config/app.php
return [
$provides => [
'Intervention\Image\ImageServiceProvider'
],
$aliases => [
'Image' => 'Intervention\Image\Facades\Image'
]
];
Step 3: Resize Image code for controller
public function resizeImagePost(Request $request) {
$this->validate($request, [
'title' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/thumbnail');
$img = Image::make($image->getRealPath());
$img->resize(100, 100, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input['imagename']);
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
$this->postImage->add($input);
return back()
->with('success','Image Upload successful')
->with('imageName',$input['imagename']);
}
I'm working on a Laravel project, and I make a feature that the user can upload image for its profile, and I use the public path to save the avatars cause 000webhost doesn't support (storage:link) and every thing works better in local
but when I upload the project on 000webhost, it refuses to upload the image and returns error (The image failed to upload.)
How can i solve it
config/filesystem.php
'public' => [
'driver' => 'local',
'root' => public_path('storage2'),
'url' => env('APP_URL').'/storage2',
'visibility' => 'public',
],
controller
public function Change(Request $request)
{
$Validate = $this->Validation($request);
if (!$Validate->fails()) {
$User = $this->getUser();
$OldImage = $User->image;
$Extension = $request->file("image")->getClientOriginalExtension();
$NewImage = str_random(30) . "." . $Extension;
Storage::putFileAs($this->privatePath, $request->file("image"), $NewImage);
$User->update(["image" => $NewImage]);
Storage::delete($this->privatePath ."/". $OldImage);
session()->flash("message", "You have changed your image");
return back();
} else {
session()->flash("error", $Validate->errors()->first());
return back();
}
}
But the problem is not in the code, cause it works in local
I think the problem with some permissions or in file .htaccess or anything like that
I want tho disply an image on my view, but i receive: File not found.
The two errors:
FileNotFoundException in FilesystemAdapter.php line 61:
storage/app/public/covers/teste-bravo_cover.jpg
FileNotFoundException in Filesystem.php line 386: File not found at
path: storage/app/public/covers/teste-bravo_cover.jpg
But the image is in the correct folder:
Well, in Laravel 5.2 storage:link won't work.
Image store on disk -works fine to store the image
if($cover){
dump("ok1");
Storage::disk('public_covers')->put($covername, File::get($cover));
$coverObject = New Cover();
//path com o nome do arquivo
$coverObject->imagePath = 'storage/app/public/covers/'.$covername;
dump($coverObject->imagePath);
}
//Salva a capa com o path para o arquivo
$coverObject->save();
My filesystems (with the "public_covers" disk) -works fine to store the image
'public_covers' => [
'driver' => 'local',
'root' => storage_path('app/public/covers'),
'visibility' => 'public',
],
View code: (if movie have cover, show them)
#if($movie->cover)
<img src="{{route('cover.image', [$movie->cover])}}" />
#endif
Route code, directing to controller method
Route::get('/movieimage/{coverId}',
[
'as' => 'cover.image',
'uses' => 'MovieController#getimage'
]
);
Controller Method to take the image
public function getimage($coverId){
$movie = Cover::find($coverId);
//dump($movie);
$imagePath = $movie['imagePath'];
dump($imagePath);
$file = Storage::disk('public_covers')->get($imagePath);
$response = Response::make($file, 200);
return $response;
}
you can try
Need to include this
use Illuminate\Support\Facades\Storage;
And set in controller or route
Route::get('storage/{filename}', function ($filename)
{
$files = Storage::files('logs'); // set repo name of storage folder
$path = storage_path('public/' . $filename);
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;
});
I am new to laravel. I had the same problem though am on laravel 5.8. I had created the symlink to display a pdf as a view but the FileNotFoundException persisted.
I ended up accessing the pdf using this url localhost:8000/storage/filename.ext.
After running ln -s /path/to/laravel/storage/public /path/to/laravel/public/storage or php artisan storage:link a storage folder is added to your appname/public directory. I think that once the link is created we access the images in the storage through the public link created. Try accessing the images via the new /appname/public/storage/app/pathtoimage folder created in the public directory and not pointing directly to the /appname/storage folder
<img src={{asset('/storage/pathtoimg')}} /> # using storage folder in public
Check this solution will work for you
How I solved my problem:
First of all, save the files on "public" folder.
On my filesystems.php i change my disk. Now my root are "public_path" and not "storage_path"
'public_covers' => [
'driver' => 'local',
'root' => public_path('images/covers'),
'visibility' => 'public',
],
My controller method
public function store(Request $request){
$cover = $request->file('cover');
$inputs = $this->request->all();
$this->validate($this->request, [
'title' => 'required|max:255',
'description' => 'required',
'gender' => 'required',
'secondGender' => 'required',
'year' => 'numeric|min:1900|max:2100',
'lenght' => 'numeric|min:10'
]);
//build movie model object
$movie = New Movie();
$movie->user_id = \Auth::user()->id;
$movie->gender_id = $inputs['gender'];
$movie->secondgender_id = $inputs['secondGender'];
$movie->title = $inputs['title'];
$movie->slug = str_slug($inputs['title']);
$movie->description = $inputs['description'];
$movie->lenght = $inputs['lenght'];
$movie->year = $inputs['year'];
//TODO Mudar a composição do nome da foto para impedir que no futuro se sobreponha uma capa com outro filme que venha a ter o mesmo nome
//TODO: Change the name createan to avoid overwrite the cover with an movie with the same name
$covername = str_slug($inputs['title']).'_cover' .'.jpg';
//if have an cover file
if($cover){
//storage the file on my public_covers (look my filesystems.php)
Storage::disk('public_covers')->put($covername, File::get($cover));
$coverObject = New Cover();
//path com o nome do arquivo
//path with the file name
$coverObject->imagePath = 'images/covers/'.$covername;
$coverObject->save();
$movie->cover_id = $coverObject->id;
}
$movie->save();
return redirect()
->route('user.dashboard')
->with([
'success' => 'Filme adicionado com sucesso!',
]);
}
My view image code
#if($movie->cover)
<img class="cover" src="{{ asset($movie->cover->imagePath) }}" alt="{{ $movie->title }}"">
#else
<img class="cover" src="{{ asset('images/noimage.jpg') }}" alt="{{ $movie->title }}">
#endif
I want to add a watermark to my uploaded image using intervention image library in laravel.I have installed it through command composer require intervention/image
, added Intervention\Image\ImageServiceProvider::class in providers array and 'Image' => Intervention\Image\Facades\Image::class in aliases array.
This is my code sample:
if($request->file1)
{
$this->validate($request, [
'file1' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
]);
$imageName = time().'-'.rand(11111, 99999).'.'.$request->file1->getClientOriginalExtension();
$imageName = $imageName->insert('https://www.exabytes.my/wp-content/uploads/400x150-exabytes-logo.png','center');
$request->file1->move('theme/img/properties', $imageName);
}
You have to actually use the Image class/facade:
$imageName = time().'-'.rand(11111, 99999).'.'.$request->file1->getClientOriginalExtension();
$file = $request->file1->move('theme/img/properties', $imageName);
$source = 'https://www.exabytes.my/wp-content/uploads/400x150-exabytes-logo.png';
Image::make($file->getPath())->insert($source, 'center');
I am trying to add a profile image feature in my app. I am using the TDD approach to do this. The test for uploading profile picture shows green. But when I run the test to update the profile picture, it gives an error. Below is the code:
Controller:
public function store(StoreAvatarRequest $request)
{
$path = $request->file('avatar')->store('avatars');
BasicInformation::updateOrCreate([
'user_id' => auth()->id(),
], [
'user_id' => auth()->id(),
'avatar' => $path,
]);
$this->showAlerts('alert-success', 'Profile Image uploaded successfully');
return redirect()->route('avatar.index');
}
public function update(StoreAvatarRequest $request, $id)
{
$basicProfile = BasicInformation::find($id)->first();
$oldAvatarPath = $basicProfile->avatar;
if ($basicProfile->user_id == auth()->id()) {
$path = $request->file('avatar')->store('avatars');
$basicProfile->avatar = $path;
$basicProfile->update();
Storage::delete($oldAvatarPath);
$this->showAlerts('alert-success', 'Profile Image Updated Successfully');
return redirect()->route('avatar.index');
} else {
// TODO :: Need to add logic here
}
}
Test Case:
public function can_update_profile_picture()
{
$this->actingAs($this->lawyer)->post(route('avatar.store'), [
'avatar' => UploadedFile::fake()->image('avatar.jpg', 600, 600)
]);
$oldImagePath = $this->lawyer->information->avatar;
$this->actingAs($this->lawyer)->put(route('avatar.update', ['id' => $this->lawyer->information->id]), [
'avatar' => UploadedFile::fake()->image('avatar1.jpg', 600, 600)
])
->assertRedirect(route('avatar.index'))
->assertSessionHas('status', 'Profile Image Updated Successfully');
Storage::disk('local')->assertExists($this->lawyer->information->avatar);
Storage::disk('local')->assertMissing($oldImagePath);
}
I am getting the following error when I run the test:
PHPUnit 5.7.19 by Sebastian Bergmann and contributors.
F 1 /
1 (100%)
Time: 298 ms, Memory: 20.00MB
There was 1 failure:
1) Tests\Feature\Dashboard\Lawyer\Account\ProfileImageTest::can_update_profile_picture
Unable to find a file at path [local/c5tjUUQDzU4iKHauJK68Z801I5iaYJ7e3cVQ5iA1.jpeg].
Failed asserting that false is true.
This is a matter of configuration and then preference for using store() or storeAs() methods.
First off you have to configure filesystems.phpto recognize your tests Storage disk as the fake() disk:
'testing' => [
'driver' => 'local',
'root' => storage_path('framework/testing/disks/'),
'visibility' => 'public',
Using that setup allows you to use your APP_ENV value in phpunit.xmlfor defaulting this disk for your tests.
Also, I use the use the storeAs()in my controller so that I can test against the filename I stored in the assertExists() method in my test.
$request->file('avatar')->storeAs('avatar', $request->file('avatar')->getClientOriginalName())
Storage::disk('avatar')->assertExists('avatar.jpg');
This is what works for me and the files are deleted before running each test and clean up is not an issue. You can also do a test for the hashName and use the store() method by getting the responsed and using baseName() to get the name of the new file.
I have added to phpunit.xml next line:
<env name="FILESYSTEM_DRIVER" value="uploads"/>
and while checking
$image = $response->original['logo']; // as the image name get changed in Controller
Storage::disk('uploads')->assertExists("public/uploads/$image");
Others codes are similar as Laravel Doc.
You may Like to check the discussion at Laracast.