php laravel What is the Stream() function in image intervention - php

I wonder what the stream() function in image intervention does? http://image.intervention.io/api/stream
Right now I am uploading my images to amazon S3 like this:
public function uploadLargeAndMainImages($file,$adId)
{
$s3 = Storage::disk('s3');
$extension = $file->guessExtension();
$filename = uniqid() . '.' . $extension;
//Create and resize images
$image = Image::make($file)->resize(null, 600, function ($constraint) {
$constraint->aspectRatio();
});
$image->encode($extension);
$imageLarge = Image::make($file)->resize(null, 800, function ($constraint) {
$constraint->aspectRatio();
});
$imageLarge->encode($extension);
// upload image to S3
$s3->put("images/{$adId}/main/" . $filename, (string) $image, 'public');
$s3->put("images/{$adId}/large/" . $filename, (string) $imageLarge, 'public');
// make image entry to DB
$file = File::create([
'a_f_id' => $adId,
'file_name' => $filename,
]);
}

Its all written in the Intervention Docs you've mentioned above:
The stream() method encodes the image in given format and given
image quality and creates new PSR-7 stream based on image data.
It returns a PSR-7 stream as instance of GuzzleHttp\Psr7\Stream.
// encode png image as jpg stream
$stream = Image::make('public/foo.png')->stream('jpg', 60);
Just for the sake of demonstration you can use the stream() method with S3 like this:
...
$image_normal = Image::make($image)->widen(800, function ($constraint) {
$constraint->upsize();
});
$image_thumb = Image::make($image)->crop(100,100);
$image_normal = $image_normal->stream();
$image_thumb = $image_thumb->stream();
Storage::disk('s3')->put($path.$file, $image_normal->__toString());
Storage::disk('s3')->put($path.'thumbnails/'.$file, $image_thumb->__toString());
It think you get it!

Related

How to encode jpeg/jpg to webp in laravel

I'm working with laravel 7 and using intervention/image to store images. However, I want to encode and store images as webp, I'm using the following code but it is not encoding the image in webp rather it is storing in the original format. Can you please tell me what I'm doing wrong?
public function storePoster(Request $request, Tournament $tournament)
{
if ($request->hasFile('poster')) {
$tournament->update([
'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
]);
$image = Image::make(public_path('uploads/' . $tournament->poster))->encode('webp', 90)->resize(200, 250);
$image->save();
}
}
Try this :
public function storePoster(Request $request, Tournament $tournament)
{
if ($request->hasFile('poster')) {
$tournament->update([
'poster' => $request->poster->store('images', ['disk' => 'public_uploads']),
]);
$classifiedImg = $request->file('poster');
$filename = $classifiedImg->getClientOriginalExtension();
// Intervention
$image = Image::make($classifiedImg)->encode('webp', 90)->resize(200, 250)->save(public_path('uploads/' . $filename . '.webp')
}
}
This is my code to convert to .webp and resize (keep image's ratio)
$imageResize = Image::make($image)->encode('webp', 90);
if ($imageResize->width() > 380){
$imageResize->resize(380, null, function ($constraint) {
$constraint->aspectRatio();
});
}
$destinationPath = public_path('/imgs/covers/');
$imageResize->save($destinationPath.$name);
if you want to convert image in to WEBP without any service or package, try this method. work for me. have any question can ask. Thankyou
$post = $request->all();
$file = #$post['file'];
$code = 200;
$extension = $file->getClientOriginalExtension();
$imageName = $file->getClientOriginalName();
$path = 'your_path';
if(in_array($extension,["jpeg","jpg","png"])){
//old image
$webp = public_path().'/'.$path.'/'.$imageName;
$im = imagecreatefromstring(file_get_contents($webp));
imagepalettetotruecolor($im);
// have exact value with WEBP extension
$new_webp = preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp', $webp);
//del old image
unlink($webp);
// set qualityy according to requirement
return imagewebp($im, $new_webp, 50);
}

Encoding format (tmp) is not supported for image resize laravel

i want to resize uploaded image and store in folder.then show in web.
i used enctype="multipart/form-data" on form in blade.php.
file successfully show in web without resize.
when try to resize image i got error
controller.php
public function dili(Request $request)
{
$di = new diligent;
$di->jobtype = $request->jobtype;
$di->jobC = $request->jobC;
$di->details = $request->details;
$image = $request->file('image');
$path = $image->getClientOriginalName();
$destinationPath = public_path('img');
Image::make($image)->resize(300, 100)->save($image);
$a = $image->move($destinationPath, $path);
$di->image = $path;
$di->save();
$de = diligent::all();
return view('admin')->with('dw', $de);
}
Error Message
Encoding format (tmp) is not supported.
1) use getRealPath() inside Image::make()
2) save image in particular path. try like this.
if($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image_resize = Image::make($image->getRealPath());
$image_resize->resize(300, 100);
$image_resize->save(public_path('img/' .$filename));
}
Make sure you installed Image intervention library.
The Intervention image save() method requires a filename so it knows what file format (jpg, png, etc..) to save your image in.
The reason you are getting the error is it does not know what encoding to save the temporary image object (tmp) in.
Here is an example
->save('my-image.jpg', 90)
There is also a optional second parameter that controls the quality output. The above outputs at 90% quality.
http://image.intervention.io/api/save

Using Intervention Image to resize an image in the storage folder

I have a function in my Laravel application that allows users to upload profile pictures to their profile.
Here is the method:
/**
* Store a user's profile picture
*
* #param Request $request
* #return void
*/
public function storeProfilePicture(User $user = null, Request $request)
{
$user = $user ?? auth()->user();
//Retrieve all files
$file = $request->file('file');
//Retrieve the file paths where the files should be moved in to.
$file_path = "images/profile-pictures/" . $user->username;
//Get the file extension
$file_extension = $file->getClientOriginalExtension();
//Generate a random file name
$file_name = Str::random(16) . "." . $file_extension;
//Delete existing pictures from the user's profile picture folder
Storage::disk('public')->deleteDirectory($file_path);
//Move image to the correct path
$path = Storage::disk('public')->putFile($file_path, $file);
// Resize the profile picture
$thumbnail = Image::make($path)->resize(50, 50, function ($constraint) {
$constraint->aspectRatio();
});
$thumbnail->save();
$user->profile()->update([
'display_picture' => Storage::url($path)
]);
return response()->json(['success' => $file_name]);
}
I am trying to use the Intervention Image library to resize the uploaded picture from the storage folder, but I always get the same error.
"Image source not readable", exception: "Intervention\Image\Exception\NotReadableException"
I have also tried with Storage::url($path) as well as storage_path($path)
Here below code work very well with the storage path, you can directly make thumb image from request and put anywhere as a desire path as follows.
Note that here I am not deleting previse stored files or directory as I am assuming that was done already.
$file = $request->file('file');
$path = "public/images/profile-pictures/{$user->username}/";
$file_extension = $file->getClientOriginalExtension();
$file_name = time(). "." . $file_extension;
// Resize the profile picture
$thumbnail = Image::make($file)->resize(50, 50)->encode($file_ext);
$is_uploaded = Storage::put( $path .$file_name , (string)$thumbnail ); // returns true if file uploaded
if($is_uploaded){
$user->profile()->update([
'display_picture'=> $path .$file_name
]);
return response()->json(['success' => $file_name]);
}
Happy coding

How to save uploaded image to Storage in laravel?

I am using Image intervention to save an image to the storage folder. I have the code below and it seems to just save a file name with a blank image. I think I need a way for the file contents to be written to the folder but struggling for the snippet.
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$img = Image::make($image->getRealPath());
$img->resize(120, 120, function ($constraint) {
$constraint->aspectRatio();
});
//dd();
Storage::disk('local')->put('images/1/smalls'.'/'.$fileName, $img, 'public');
You need to do
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$fileName = time() . '.' . $image->getClientOriginalExtension();
$img = Image::make($image->getRealPath());
$img->resize(120, 120, function ($constraint) {
$constraint->aspectRatio();
});
$img->stream(); // <-- Key point
//dd();
Storage::disk('local')->put('images/1/smalls'.'/'.$fileName, $img, 'public');
}
if ($request->hasFile('photo')) {
// $path = Storage::disk('local')->put($request->file('photo')->getClientOriginalName(),$request->file('photo')->get());
$path = $request->file('photo')->store('/images/1/smalls');
$product->image_url = $path;
}
Simple Code.
if($request->hasFile('image')){
$object->image = $request->image->store('your_path/image');
}
Thanks.
Here is another way to save images using intervention package on storage path with desired name. (using Storage::putFileAs method )
public function store(Request $request)
{
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$image_name = time() . '.' . $image->extension();
$image = Image::make($request->file('photo'))
->resize(120, 120, function ($constraint) {
$constraint->aspectRatio();
});
//here you can define any directory name whatever you want, if dir is not exist it will created automatically.
Storage::putFileAs('public/images/1/smalls/' . $image_name, (string)$image->encode('png', 95), $image_name);
}
}

Can't write image data to path. Intervention Image Laravel 5.2

public function newItem(Request $request){
$image = $request->file('image');
$img = time().'.'.$image->getClientOriginalExtension();
$watermark = Image::make('images/watermark.png');
$destinationPath = public_path('/products');
$img = Image::make($image->getRealPath());
$img->resize(300, 365, function ($constraint) {
$constraint->aspectRatio();
})->insert($watermark, 'center');
File::exists($destinationPath) or File::makeDirectory($destinationPath);
$img->save($destinationPath.'/'.$img);
}
I keep getting Can't write image data to path
Can anyone figure out what I'm doing wrong?
The question might seem duplicate, but other suggestions in similar questions did not work for me.
Thanks in advance
For the sake of others that might have the same issue. This is how I solved it:
$image = $request->file('image');
$img = time().'.'.$image->getClientOriginalExtension();
$watermark = Image::make('images/watermark.png');
$destinationPath = public_path('/products');
Image::make($image->getRealPath())->resize(300, 365, function ($constraint) {
$constraint->aspectRatio();
})->insert($watermark, 'center')->save($destinationPath.'/'.$img);
The mistake I was making was assigning Image::make() to a variable. You can look at my code here and the one above in my question.
Try this code it's worked for me
public function newItem(){
$image = Input::file('image');
$destinationPath = '/products';
$img = time().'.'.$image->getClientOriginalExtension();
$watermark = Image::make('images/watermark.png');
$img = Image::make($image->getRealPath());
$img->resize(300, 365, function ($constraint) {
$constraint->aspectRatio();
})->insert($watermark, 'center');
File::exists($destinationPath) or File::makeDirectory($destinationPath);
$img->save($destinationPath.'/'.$img);
}
Make sure to create mentioned path folders (passing with image save) in laravel public folder. This will work automatically.
If somebody use File Facade:
File::exists($destinationPath) or File::makeDirectory($destinationPath);
You have to remember that if your $destinationPath contains more than 1 folder, you have to set 2nd & 3rd parameters like $mode & $recursive to create final destination folder and prepare directory for file upload.
Example:
File::exists($imagePath) or File::makeDirectory($imagePath, 777, true);

Categories