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

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more