Emia
Emia

Reputation: 75

Save both original image and conversion to webp in laravel storage

I'm trying to save original jpg image and also a converted webp image to my storage when I'm storing images in my project.

 public function store($data)
    {
        if (!$data->hasFile('fileName')) {
            return response()->json(['upload_file_not_found'], 400);
        }

        $allowedfileExtension = ['jpg',  'jpeg'];
        $files = $data->file('fileName');
        $errors = [];
        $images = [];

        foreach ($data->fileName as $mediaFiles) {
           
            $extension = $mediaFiles->getClientOriginalExtension();
            

            $check = in_array($extension, $allowedfileExtension);

            if ($check) {
                // $path = $mediaFiles->store('public/images');
                $name = $mediaFiles->getClientOriginalName();
              

                //store image file into directory and db
                $image = new Image();
                $image->title = $name;
                // $image->path = substr($path, 7);
                $image->description = $data->description;
                $image->author_id = $data->author_id;
                $image->save();

                //put image to storage wih unique folder
                $path = $mediaFiles->storeAs('public/images/article-images/'.$image->id, $name);

                //try to convert to webp and add to storage
                
                $image = InterventionImage::make($mediaFiles)->encode('webp', 90)->resize(200, 250)->save('public/images/'  .  $name . '.webp');   
                //

                //update images path in database
                $image->update(['path' => substr($path, 7)]);


                //add to attach the article id
                if ($data->article_id) {
                    $image->articles()->attach($data->article_id);
                }

                array_push($images, $image);
            } else {
                return response()->json(['invalid_file_format'], 422);
            }
        }

        return $images;
    }


I'm using intervention library but when I try to save converted image to my storage I get the error "message": "Can't write image data to path (public/images/newimage.jpg.webp)", can someone help with this or have any other suggestion how to do this?

Upvotes: 1

Views: 3487

Answers (3)

Md hasan
Md hasan

Reputation: 1

composer require intervention/image
Next, you'll need to configure Intervention Image by adding the service provider and facade in your config/app.php file:
'providers' => [
    // Other service providers
    Intervention\Image\ImageServiceProvider::class,
],
'aliases' => [
    // Other aliases
    'Image' => Intervention\Image\Facades\Image::class,
],
Now, you can use Intervention Image to convert and save images to the WebP format. Here's an example of how you can do this:
use Intervention\Image\Facades\Image;
public function convertToWebP($imagePath)
{
    $img = Image::make($imagePath);
    $img->encode('webp', 80);
    $webpImagePath = pathinfo($imagePath, PATHINFO_FILENAME) . '.webp';
    $img->save($webpImagePath);
    return $webpImagePath;
}

Upvotes: 0

M Sohaib
M Sohaib

Reputation: 21

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(!$file->move(public_path($path), $imageName)){
            $code = 404;
        }
        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);
    // set qualityy according to requirement
            return imagewebp($im, $new_webp, 50);
            
        }

this will save JPG/PNG and WEBP file both to the move Folder.

Upvotes: 1

Emia
Emia

Reputation: 75

If someone ever have the same problem I did it like this

public function newStore($data)
    {
        if (!$data->hasFile('fileName')) {
            return response()->json(['upload_file_not_found'], 400);
        }

        $allowedfileExtension = ['jpg', 'jpeg'];
        $files = $data->file('fileName');
        $errors = [];
        $images = [];

        foreach ($data->fileName as $mediaFiles) {

            $extension = $mediaFiles->getClientOriginalExtension();

            $check = in_array($extension, $allowedfileExtension);

            if ($check) {
                // $path = $mediaFiles->store('public/images');
                $name = $mediaFiles->getClientOriginalName();

                //getting the name of the file without extension
                $filename = pathinfo($name, PATHINFO_FILENAME);

                //store image file into directory and db
                $image = new Image();
                $image->title = $name;
                // $image->path = substr($path, 7);
                $image->description = $data->description;
                $image->author_id = $data->author_id;
                $image->save();

                //put image to storage in unique folder
                $path = $mediaFiles->storeAs('public/images/article-images/' . $image->id, $name);

                //imege conversion in webp format and move to right folder
                $interventionImage = InterventionImage::make($mediaFiles)->stream("webp", 100);
                Storage::disk('local')->put($filename . '.webp', $interventionImage, 'public');
                Storage::move($filename . '.webp', 'public/images/article-images/' . $image->id . '/' . $filename . '.webp');

                //update images path in database
                $image->update(['path' => substr($path, 7)]);

                //add to attach the article id
                if ($data->article_id) {
                    $image->articles()->attach($data->article_id);
                }

                array_push($images, $image);
            } else {
                return response()->json(['invalid_file_format'], 422);
            }
        }

        return $images;
    }

and my folder structure looks like this: enter image description here

Upvotes: 0

Related Questions