Cloudinary Blog

Compressing, Resizing, and Optimizing Videos in Laravel

Compressing, Resizing, and Optimizing Videos in Laravel

Videos are large media files—in most cases, at least four times larger than images—and are often created for ads, marketing campaigns, and instructional content to convey as much information as possible in a short time. Ensuring that videos do not buffer all the time and that the user’s data is protected from rapid consumption due to heavy page weight must be the modus operandi for all website builders and e-business owners.

This article shows you how to optimize videos in Laravel.

Set Up a Laravel Project

1. Install Composer and PHP on your development or production machine and then run this command:

Copy to clipboard
composer create-project --prefer-dist laravel/laravel video-optimization

2. Go to the video-optimization directory and rename the env.example file to .env.

3. Run the project with the command php artisan serve.

Your Laravel project is now up and running.

Set Up Cloudinary’s Laravel SDK

With Cloudinary, you can efficiently optimize media assets—regardless of programming language. One reason is that, by default, Cloudinary automatically performs certain optimization steps on all transformed images. Plus, its integrated, fast-delivery capability through content delivery networks (CDNs) ensures that your images are seamlessly displayed on your viewers’ devices.

To enable video uploads and optimization with Cloudinary:

  1. Sign up for a free Cloudinary account, log in, and note your cloud name and API keys from the dashboard.

    media library

  2. Install Cloudinary’s Laravel SDK:

Copy to clipboard
composer require cloudinary-labs/cloudinary-laravel

Important: Be sure to follow the steps in the #Installation section. Publish the configuration file and add your Cloudinary credentials to the .env file of your app.

Set Up the Mechanics for Video Uploads

1. Create a video-upload controller (VideoUpload Controller) in your project:

Copy to clipboard
php artisan make:controller VideoUploadController

2. Open the VideoUploadController.php file and add a method for displaying the upload form:

Copy to clipboard
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class VideoUploadController extends Controller
{
    public function showUploadForm()
    {
        return view('upload');
    }
}

3. Create an upload.blade.php file in the resources/views directory and populate the file with the code below:

Copy to clipboard
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel Video Upload</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
    <body>
        <div class="flex-center position-ref full-height">
            <div class="content">
                <div class="title m-b-md">
                    Laravel File Upload
                </div>

                @if ($message = Session::get('success'))
                    <div class="alert alert-success alert-block">
                        <button type="button" class="close" data-dismiss="alert">×</button>
                            <strong>{{ $message }}</strong>
                    </div>
                @endif

                <div class="links">
                     <form action="/upload" method="POST" enctype="multipart/form-data">
                        @csrf
                        <div class="row">

                            <div class="col-md-6">
                                <input type="file" name="video" class="form-control">
                            </div>

                            <div class="col-md-6">
                                <button type="submit" class="btn btn-success">Upload a Video</button>
                            </div>

                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

On a successful upload, the code above displays the form along with a confirmation message. Concurrently, the code posts the form data to an /upload route in the routes/web.php file.

Note
You'll see the related code later in this post.

4. Go to the routes/web.php directory and add two routes: one to display the form and the other to process the file upload:

Copy to clipboard
Route::get('/upload', 'VideoUploadController@showUploadForm');
Route::post('/upload', 'VideoUploadController@storeUploads');

Now reload the app and go to the /upload route. This page is then displayed:

Laravel File upload

Compress and Resize Videos on Upload

Create an upload method in the VideoUploadController.php file to ensure that compression and resizing of user-uploaded images occur by default on upload.

The code below resizes a video to 350 pixels in width and 200 pixels in height:

Copy to clipboard
public function upload(Request $request)
{
     $resizedVideo = cloudinary()->uploadVideo($request->file('video')->getRealPath(), [
            'folder' => 'uploads',
            'transformation' => [
                      'width' => 350,
                      'height' => 200
             ]
])->getSecurePath();

    dd($resizedVideo);
}

Optimize Videos on Upload

To consistently deliver the highest-quality videos with the smallest file sizes, follow the steps below.

Quality

Compress and optimize the quality of a video file with the code below:

Copy to clipboard
public function upload(Request $request)
{
     $compressedVideo = cloudinary()->upload($request->file('video')->getRealPath(), [
            'folder' => 'uploads',
            'transformation' => [
                      'quality' => auto,
             ]
])->getSecurePath();
dd($resizedVideo);
}

Setting the auto value for the quality attributes automatically compresses and optimizes the video, balancing its visual quality. You can specify any of the auto options below:

  • q_auto: The optimal balance between the file size and visual quality. By default, this algorithm is the same as q_auto:good.
  • q_auto:best: A less aggressive algorithm that generates bigger files with potentially higher visual quality.
  • q_auto:good: An algorithm that ensures a relatively small file size with good visual quality.
  • q_auto:eco: A more aggressive algorithm, which results in smaller files of slightly lower visual quality. Examples of the target audience are popular sites and social networks with heavy traffic.
  • q_auto:low: The most aggressive algorithm, which results in the smallest files of low visual quality. Examples of the target audience are sites with thumbnail previews that link to higher-quality videos.

As an illustration, here’s the original, uncompressed video with a size of 8.3 MB:

Here’s the compressed version with a size of 5.9 MB:

Visually, there’s almost no difference between the two videos even though the second one is only slightly more than half the size of the first one.

Format

Compress and optimize the video file by selecting the best video format for delivery on the client:

Copy to clipboard
public function upload(Request $request)
{
     $compressedVideo = cloudinary()->upload($request->file('video')->getRealPath(), [
            'folder' => 'uploads',
            'transformation' => [
                      'fetch_format' => auto,
             ]
])->getSecurePath();

dd($resizedVideo);
}

Setting fetch_format to auto instructs Cloudinary to deliver the best format that saves bandwidth and to optimize delivery time by selecting the appropriate format and codec based on the browser or client that requests the video. For instance, Chrome would attempt to deliver a VP9-encoded WebM file; Safari, an HEVC-encoded MP4 file. Other browsers would attempt to deliver an H.264-encoded MP4 file, especially if they don’t support the first two types of video encoding that work on Chrome and Safari.

Optimize Videos on Streaming

You can continuously optimize video quality during streaming with the adaptive bitrate (ABR) delivery technique, which adjusts the quality of a video stream in real time according to the detected bandwidth and CPU capacity. That way, videos can start faster with fewer buffering interruptions and with the highest quality for the current device and network connection, resulting in an optimal user experience.

Furthermore, Cloudinary can automatically generate and deliver all those files from a single original video, transcoded to either or both of these two protocols:

  • HTTP Live Streaming (HLS)
  • Dynamic Adaptive Streaming over HTTP (MPEG-DASH)

For details on how to optimize videos with the ABR technique, see the Cloudinary Adaptive Streaming Guide.

Leverage More Cloudinary Capabilities

Cloudinary helps you administer the entire spectrum of your media’s lifecycle, end to end, from upload and transformation to optimization and delivery. Do check it out.

Recent Blog Posts

Auto-Tag Videos With Cloudinary: A Tutorial

Video is one of the best ways for capturing audience attention. Product demonstrations, property tours, tutorials, and keynotes all make great content—provided that they’re readily searchable by your team and visitors alike. Even though tagging and categorization help organize videos and make them easy to find, the labeling process is labor intensive, taking time away from key tasks like creating new videos.

Read more
Video Uploads With Cloudinary

Setting up the infrastructure for video uploads can go from straightforward to complex real fast. Why? Because many challenges are involved in building a foolproof service for an efficient and smooth process.

Read more
Optimize Media to Get Ready for Google’s Core Web Vitals

For years, Google has been updating its search algorithm to prioritize end-user experience, displaying the most relevant and helpful content at the top of search results. The latest—and maybe the most significant—update so far is Core Web Vitals (CWVs), which are new metrics announced a year ago that will, starting in June, begin determining search rankings. With this update, Google is being abundantly clear that visual experience of webpages is paramount.

Read more
Five Ways to Effectively Manage Online Media

The digital economy is driven by highly visual experiences. After all, viewers process images 60,000 times faster than text. Therefore, it’s no surprise that top-notch visual media has been an essential component of a captivating e-commerce experience for years. Nor is it surprising that visual media’s importance only rose during the COVID-19 pandemic, a reality for all retailers, including our client Levi’s.

Read more
Creating an API With Python Flask to Upload Files to Cloudinary

Code

Cloudinary offers SDKs for many programming languages and frameworks. Even though it also offers an Upload API endpoint for both back-end and front-end code, most developers find the SDKs very helpful. If you're working with a powerful back-end framework like Python Flask, you'll be happy to hear that a Python SDK is now available.
This tutorial walks you through the process of building an API to upload images to Cloudinary. You can also upload other file types, including video and even nonmedia files, with the API.

Read more
How to Use the Cloudinary Media Editor Widget

At Cloudinary, we manage the entire pipeline of media assets for thousands of customers of varying sizes from numerous verticals.

As part of our commitment to support the entire flow of media assets, we are now introducing an intuitive media editing widget: an out­-of­-the-­box, interactive UI providing your users with a set of common image editing actions for immediate use on your website or web app. The widget is interactive and simple, built on Cloudinary's transformation capabilities, and requiring only a few lines of code to integrate. Afterwards, you can seamlessly and effortlessly add content to your site or app with no need for in-house image editing capabilities.

Read more