A Guide To Upload And Compress Images In Laravel

Are you looking for upload and compress images in Laravel? Laravel provides an easy way for file uploading and using TinyPNG we can compress the uploaded images. In this article, we show you how to upload and compress images in Laravel.

Why Need To Compress Images?

Images play an important role for your website. Images add better UX for your site but can also kill the site performance. Heavy images slow down the site. As a result, your site takes a long time to load. Users don’t like the slow site. If your site taking more time to load, it is a high chance you lose your audiences. Standard loading time for a site is 2 seconds. You should take care of your site is loading within 2 seconds.

Compressing images reduce the size of your image without losing quality. By this way, you save some amount of image size which helps to increase your site speed.

How To Upload Images In Laravel

Laravel provides a clean way to upload the images. To store our images we first need to create a directory where we store all uploaded files. To do this, open your command prompt in the project directory and run the below command.

php artisan storage:link

Above command create ‘storage’ directory under the ‘public’ folder.

Let’s create a form with the file input and submit button.

<form action="{{ url('PASS_ACTION_URL') }}" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="exampleInputFile">File input</label>
        <input type="file" name="profile_image" id="exampleInputFile">
    {{ csrf_field() }}
    <button type="submit" class="btn btn-default">Submit</button>

In our HTML we have added file input with the name ‘profile_image’. We also added {{ csrf_field() }} which is necessary in Laravel.

Now, we are assuming you send the post request to your controller method store(). So, write a file uploading code in this function.

public function store(Request $request)
    if($request->hasFile('profile_image')) {
        //get filename with extension
        $filenamewithextension = $request->file('profile_image')->getClientOriginalName();

        //get filename without extension
        $filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);

        //get file extension
        $extension = $request->file('profile_image')->getClientOriginalExtension();

        //filename to store
        $filenametostore = $filename.'_'.time().'.'.$extension;

        //Upload File
        $request->file('profile_image')->storeAs('public/profile_images', $filenametostore);

        //We will write TinyPNG Compress Image Code Here

        return redirect('images/create')->with('success', "Image uploaded successfully.");

Above code create a unique filename and store it in ‘profile_images’ folder. Laravel automatically creates ‘profile_images’ directory under ‘public/storage’.

TinyPNG Comes In Picture

At this point, we have completed our file uploading task. We are just moving a file to the destination folder. No matter what the size file has.

Now, we need to write code which will compress a uploaded image.

To compress images using TinyPNG you should get developer key from their official website. The process is straight-forward. You just need to register with your email address and they will send your developer key.

Once you have your developer key, you need to install package for tinify/tinify. Open your command prompt and run the below command.

composer require tinify/tinify

Running above command will install tinify library in your project.

Compress Images Using TinyPNG In Laravel

Now, we are ready with our tinify package. Next step is the write a code which compress the uploaded image.

We need to write compression code just below the line which uploads the image.

//TinyPNG Compress Image
$filepath = public_path('storage/profile_images/'.$filenametostore);

try {
    $source = \Tinify\fromFile($filepath);
} catch(\Tinify\AccountException $e) {
    // Verify your API key and account limit.
    return redirect('images/create')->with('error', $e->getMessage());
} catch(\Tinify\ClientException $e) {
    // Check your source image and request options.
    return redirect('images/create')->with('error', $e->getMessage());
} catch(\Tinify\ServerException $e) {
    // Temporary issue with the Tinify API.
    return redirect('images/create')->with('error', $e->getMessage());
} catch(\Tinify\ConnectionException $e) {
    // A network connection error occurred.
    return redirect('images/create')->with('error', $e->getMessage());
} catch(Exception $e) {
    // Something else went wrong, unrelated to the Tinify API.
    return redirect('images/create')->with('error', $e->getMessage());

Above code take an image from the uploaded directory, send it to TinyPNG API for compression and again store the compressed image in the same directory. If in case some errors occurred, then we have handled those errors.

This all process runs in the background. You don’t need to worry about how image send to REST API? how can we get the API response?. Tinify library does all tasks for you.

We hope you understand how to upload and compress images in Laravel. If you have any questions or suggestions please leave a comment below.

If you liked this article, then please subscribe to our Youtube Channel for video tutorials.

Recommended Tutorials For You

Leave a Reply

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