Connect with us

How to convert image from png, jpg to webp image in Laravel

kizinho

Published

on

Follow
DEVELOPER PROGRAMMING: How to convert image from png, jpg to webp image in Laravel [New  Developer Programming] » Naijacrawl
Photo: Naijacrawl
site

Hi, folks will show how you can convert any image to webp image.

Why Webp

WebP is making headway in the image format space this year. The image format — which is developed by Google — uses both lossy and lossless compression by utilizing technology that Google purchased from On2 Technologies.


WebP has been around a while now, actually, and it first made headlines in a 2010 Google press conference. But, like any new technology, it had some initial rough patches. Today, WebP is on version 1.0.0, so we thought it would be a great time to talk about what makes WebP so powerful, and why it’s a fantastic option for web designers and developers.

a

Before I proceed to describe what WebP actually is, let us focus on why it matters—it’s not only about making images smaller, but it’s also about why and how the images need to be made smaller.


You may have heard about design mistakes killing your SEO and conversion rates. While there are some aspects that CSS or JavaScript are responsible for, like blocking rendering, the images nowadays are a huge part of any website’s weight. Therefore, users on slower connections will have trouble interacting with your website (unless it’s an AMP).

Just recently, It’s an interesting area of expertise, where you take care of lots of small things to deliver one big thing—a superfast, superlight website that reads on any device and looks amazing at the same time.


Chances are, you’ve seen WebP images before. If you open Naijacrawl in Google Chrome, all of those thumbnails are going to be WebP thumbnails. If you were to open the Facebook app on your android phone, all of the images that you see would be WebP. It’s definitely being utilized by various companies around the world to increase performance.


So let's see how you can do the same using laravel to convert your images to webp image.


Note this works in all laravel versions


I assumed you have a project already or you can create one by using this command


composer create-project 
laravel/laravel webimage
 --prefer-dist


You must have installed a composer before you can run the command.


We need a controller so let's create one

php artisan make:controller 
ImageWebpController


Inside the controller, we will write a code that will process our image and convert it to webp inside a folder


What it Requires

file extension

file name

folder


namespace
 App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class ImageWebpController 
extends Controller {
public function webpImage
(Request $request) 
{
if ($request->hasFile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); 
$rand = '-' . strtolower(Str::random(10));  
$name = $rand . '.' . $extension;   
return $this->processImage($file, $name);  
 }  
  }    
private function processImage
($file, $name) 
{  
$file->move(public_path('/test/image'), 
$name);  
      //convert to webp         
$webp = public_path() . '/test/image/' .
 $name;      
  $im = imagecreatefromstring
(file_get_contents($webp)); 
 $new_webp =
 preg_replace('"\.(jpg|jpeg|png|webp)$"',
 '.webp', $webp);  
imagewebp($im, $new_webp, 50);  
 return'message'
 => 'image successfully 
converted to webp.
 check your 
folder to see it'
];   
 }
}
?>

from what i did, i check if the request is a file before proceeding , have to get extension of the file and use it make a slug name for the image, because i don't want it to carry original name.

$extension = $file->
getClientOriginalExtension();

I have to use str function to form a characters for the name of the image

 $rand = '-' . 
strtolower(Str::random(10));

//final name
$name = $rand . '.' . $extension;

I needed another private function because i want to separate my code for easy to read using processImage function.


 private function processImage
($file, $name) {
$file->move(public_path('/test/image'),
 $name); 
       //convert to webp         
$webp = public_path() . '/test/image/' .
 $name;
 $im = imagecreatefromstring
(file_get_contents($webp));  
$new_webp =
 preg_replace('"\.(jpg|jpeg|png|webp)$"', '.webp',
 $webp);
imagewebp($im, $new_webp, 50);        
return'message' 
=> 'image successfully 
converted to webp. 
check your folder 
to see it' ];  
  }
?>

After i called it to the main function which

is webpImage function .

Inside processImage function ,

the file is moved to my public folder called test/image before converting it to webp image

//get image that
 we want to convert 
$webp = public_path() .
 '/test/image/' . $name;
//create the image        
$im = imagecreatefromstring
(file_get_contents($webp));
//accept image extensions of jpg,png,webp 
$im = imagecreatefromstring
(file_get_contents($webp));
 $new_webp = 
preg_replace('"\.(jpg|jpeg|png|webp)$"', 
'.webp', $webp);
//make the webp image and set the quality to 50 
//the more quality the more it becomes broght and increase mb
// you can set to 100 which means no quality will be reduced 
 imagewebp($im, $new_webp,50);
?>

From my code i didn't add validation rule which you can do it if you needed it , just to make it allow only files and extension type


Find this article helpful kindly share it.

Click Here To Comment


site


kizinho

Adike Kizito is a top-rated software developer, blogger, sports, and entertainment lover. He is the CEO of these popular websites Naijacrawl.com and Mp3ager.com. He operates his software developing task through Kizzsoft.com,... Read More

Continue Reading
Click to comment

Be first to comment


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    Laravel 8 is now released!

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: Laravel 8 is now released! [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl
    Laravel 8 is now released and includes many new features including Laravel Jetstream, a models directory, model factory classes, migration squashing, rate-limiting improvements, time testing helpers, dynamic blade components, and many more features.Before we jump into the new features, we’d like to point out that starting with version 6, Laravel now follows semver and will release a new major version every six months. You can see how the release process works here.L...
    Continue Reading

    How to fix Flutterwave common error's while Integrating payment in your Laravel App

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: How to fix Flutterwave common error's while Integrating payment in your Laravel App [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl
    Hi folks, I was integrating FLutterwave on my laravel app, on the process i found a bunch of errors while trying to use it accept payment on my site. Have been a Paystack heavy user but decided to use Flutterwave for a reason that I love to do. Going through this article I will list the two types of error or bug that you must encounter while using Laravel Rave steps to get Flutterwave payment working.Types of errorError on the payment page when user try to refresh t...
    Continue Reading

    Easy way to Host your Laravel Application on Shared Hosting

    kizinho

    Published

    on

    DEVELOPER PROGRAMMING: Easy way to Host your Laravel Application on Shared Hosting [New  Developer Programming] » Naijacrawl
    Photo: Naijacrawl
    Hi , Folks have you finished building that your awesome project but hosting it o shared hosting is what remains, don't worry you are on the right track, I have the best way to do that.StepsCreate Database on your online cpanelUpload your project or use git to do thatSet everything up on your ENVnow we need .htaccess that you will create inside your laravel root folderInside the .htaccess add this code RewriteEngine On #ends RewriteCond %{HTTP_HOST} ^(www.)?mydomain...
    Continue Reading

    Latest


    Download Naijacrawl App today

    Fastest way to read on the go

    Download the Naijacrawl App.