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

Automate the Staging Process of Videos for Social Media

Rich and engaging media helps build customer engagement and trust but can be time consuming to stage. Developers save a tremendous amount of time by preparing videos for social media with Cloudinary. That’s because Cloudinary’s interface, widgets, and application programming interface (API) transform raw media into polished content, optimizing footage and enabling effortless customization and publishing.

Read more

Top Five Web-Video Formats of 2021

By William Imoh
The Five Most Popular Web-Video Formats and Streaming Protocols

Over the past 15 years, the video industry has undergone a significant change in video formats on the web. In particular, in the early 2010s, the 3GP format, which the 3rd Generation Partnership Project (3GPP) created for 3G-enabled mobile devices, went nearly extinct. The advancement of mobile devices and cellular networks has brought about the need for pioneers to build better formats for a faster user experience.

Read more
Cloudinary Introduces Integration With SAP Commerce Cloud

We’re excited to announce Cloudinary’s integration with SAP Commerce Cloud, through which the latter’s customers can significantly boost the visual media experience on their website or app.

SAP Commerce Cloud powers some of the largest e-commerce sites (B2C, B2B, and B2B2C businesses), complete with building blocks like storefront design and order management. Reinforced with Cloudinary’s laser-sharp focus on optimizing, managing, and delivering images and videos, the new extension will enable SAP Commerce Cloud customers to create unique and engaging visual experiences effortlessly.

Read more
Personalizing Video Email for Marketing Campaigns With Cloudinary

As critical as it is to engage with shoppers in order to succeed in e-commerce, old-style, boring emails are far from being effective. In fact, they tend to be annoying because no one likes to read formulaic, generic messages that are sent en masse. For better results, rethink your email marketing campaigns and try out creative strategies.

Read more
Muted Videos and Subtitles

The bane of our existence is the lack of efficient ways for tackling the plethora of recurring tasks in our lives. One of those tasks is surfing the internet. We consume a lot of web content daily, of which a large percentage are images and videos. We’re constantly quickly scrolling through 30-second videos or checking out pictures of cute items we’d like to buy in our free time.

Read more

Building a Roommate-Matching App With Cloudinary and Jamstack

By Marcelo Ricardo de Oliveira
Building a Roommate-Matching App With Cloudinary and Jamstack

Roommate matching can be a pain—especially during the COVID pandemic when people don't want to meet in person. Matching apps like Flatmates, Roomster, and roommates.com are helpful, and if you're in the roommate-matching space, you know that great video is essential for those seeking roommates. Fortunately, Cloudinary can help.

Read more