DEV Community

Riccardo Savio
Riccardo Savio

Posted on

Convert images in Webp

Allow users to upload an image in JPEG, PNG, JPG, or GIF format, convert it to the WebP format, and save it on your server.

This code performs a series of operations:

  • It checks whether the user has uploaded a valid image.
  • It generates a unique name for the WebP image based on the current time.
  • It converts the uploaded image into an image object.
  • If the conversion is successful, the image is converted to the WebP format and saved on the server.
  • The name of the WebP file is saved in the database.
  • In case of an error, the user receives an error message.
try {
    // Validation for the uploaded image
    $request->validate([
        'img_path' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048'
    ]);

    if ($request->hasFile('img_path')) {
        // Get the uploaded image
        $image = $request->file('img_path');

        // Generate a unique name for the WebP file based on the current time
        $imageName = time() . '.webp';

        // Path where the WebP file will be saved
        $webpPath = public_path('storage/images/' . $imageName);

        // Create an image object from binary data
        $imageResource = imagecreatefromstring(file_get_contents($image->path()));

        // Check if the conversion was successful
        if ($imageResource === false) {
            throw new \Exception("Error during image conversion.");
        }

        // Convert and save the image in WebP format
        if (!imagewebp($imageResource, $webpPath, 90)) {
            throw an \Exception("Error during WebP image saving.");
        }

        // Save the WebP file name in the database
        $imgModel = new Image();
        $imgModel->img_path = $imageName;
        $imgModel->save();

        return redirect()->back();
    }
} catch (\Exception $e) {
    // In case of an error, display an error message to the user
    return redirect()->back()->with('error', $e->getMessage());
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)