Video optimization for the web simplified with ImageKit
Publikováno: 21.9.2021
Learn how you can resize and optimize video assets using ImageKit's URL-based video APIs.
The post Video optimization for the web simplified with ImageKit appeared first on Codrops.
It is easy to convey a complex idea through a video.
For example, this landing page of a developer-focused tool demonstrates the real-time resizing of images using URL parameters. However, to present the same idea using a static image would have been slightly tricky.
There are obvious benefits of using videos in terms of getting user’s attention. But, using videos on the web introduces performance problems. Video files use more bytes and take longer to transfer. This becomes a problem for viewers, especially on mobile phones with slow network connection speed.
As web developers, we need to ensure that the viewer experience doesn’t deteriorate because our marketing team wants to use videos. This reiterates the fact that video optimization for the web is an inevitable concern.
What is video optimization?
Simply put, video optimization is a set of techniques to reduce video size in bytes without negatively impacting perceived video quality. We will talk about how you can use different techniques in this post.
Importance of optimizing videos on the website
Before we jump right into the core, Here’s an interesting fact: The median video bytes have increased from 768KB to 2.0MB on mobile in the last two years on 7.4M URLs analyzed by httparchive.org.
This trend will continue in the future as more and more businesses leverage videos to gain user attention.
If we optimize videos, it can have a substantial bandwidth saving that will translate into better website performance which in return will improve the user’s experience.
Techniques to optimize video for the web
First, let me give you a cheat sheet that you can refer to, and then we will talk about each of the following items in more detail:
- Correct preload attribute value:
- If there is a high chance that the video will be watched, use preload:auto. This will leave the decision to load video content to the browser.
- If there is a low chance that the video will be watched, use preload:none. It won’t load any bytes. For third-party videos embedded on your page, always use this.
- If you are unsure and want to balance playback speed and bandwidth consumption, use preload: metadata. This will only load metadata, allowing the browser to issue a byte-range request later to start playback.
- Remove audio from silent videos It might sound obvious. Still, there is a good chance that you are using muted attribute and the underlying video file has an audio channel that is consuming extra bytes. Using ImageKit.io, you can pass ac-none query parameters in the URL to remove the audio channel.
- Load correctly sized videos Now, this is a very important point. Consider this, delivering a small size video on mobile compared to desktop. The video will download faster, use less data on mobile (of course, less battery consumption). Using ImageKit.io’s URL-based video manipulation parameters, you can resize the video to the desired dimension in the HTML without dealing with any resizing software.
- Compress videos the right way You should compress the video and export it to multiple video formats, including WebM, MPEG-4/H.264. It is essential to do this right as any hiccup here can hurt the user’s experience & the content conveyed. We will learn soon how you can automate this completely using ImageKit.io without writing any code.
- Optimize <source> order Put the smallest video first and the largest last. For example, video compressions in three different formats at 10MB, 12MB, and 13MB declare the smallest first and the largest last.
<video width="400" height="300" controls="controls">
<!-- WebM: 10 MB -->
<source src="video.webm" type="video/webm" />
<!-- MPEG-4/H.264: 12 MB -->
<source src="video.mp4" type="video/mp4" />
<!-- Ogg/Theora: 13 MB -->
<source src="video.ogv" type="video/ogv" />
</video>
- Ensure there is no wasteful downloading of videos While implementing webpage for desktops, we often forget about small screen devices. If you do not want to play video on the small screen, ensure that the video element is not visible by display:none so that browser doesn’t trigger any video requests for mobile devices.
Automate video optimization and simplify resizing
If you are someone using a good number of videos on your website optimizing them one by one for the varied set of user devices might seem a tedious task! And thus this calls for automating video optimization for optimal performance.
ImageKit.io is a cloud-based service that offers URL-based video APIs to resize and optimize video assets.
Most of the methods you have learned so far are related to correct attributes and CSS classes. However, the three most important ones require you to modify the video content:
- Load correctly sized videos. It means multiple variants based on the device.
- Compress video using correct codec and format.
- Remove audio from silent videos.
Tools like FFmpeg can help you with the above three tasks, but it will be cumbersome if you have tons of videos. Not to mention hundreds of options in the FFmpeg manual will not make your job easy.
ImageKit.io’s video API to rescue!
Real-time video resizing API
ImageKit offers comprehensive capabilities covering all the commonly used video transformations you will need for your web applications.
Here are a few examples:
Resize videos – Basic height & width manipulation
Let’s assume we have an original video which is 1280x720px
<https://ik.imagekit.io/demo/sample-video.mp4>
To get a 300px wide video, we will add a tr query parameter with value w-300 as shown below:
https://ik.imagekit.io/demo/sample-video.mp4?tr=w-300
Notice that height is automatically adjusted to maintain the aspect ratio.
Similarly, you can use the h (height) parameter to adjust the video’s height and width according to aspect ratio.
Cropping & preserving the aspect ratio
If only one of the height(h) or width(w) is specified, then ImageKit.io adjusts the other dimension accordingly to preserve the aspect ratio, and no cropping occurs.
But when you specify both height(h) and width(w) dimension and want to preserve the aspect ratio – you have the following three options:
- Crop some part of the video. You can choose which area to crop by controlling the focus point.
- Add padding around the video. You can control the background color of the padding to match the layout.
- Let ImageKit change either height or width so that the whole video content is visible. In this case, only one of the heights or widths matches the request dimension.
ImageKit offers a wide variety of video cropping strategies to get your desired output. Let’s understand different cropping options with examples.
No cropping – forcefully fitting the image in requested dimensions.
If you need an image in the exact dimension as requested, even if the aspect ratio is not preserved, use the c-force parameter.
URL – https://ik.imagekit.io/demo/sample-video.mp4?tr=w-200,h-200,c-force
Notice that the aspect ratio is changed and the video looks squeezed.
Default center cropping
This is the default crop strategy. If nothing is specified in the URL, this strategy gets applied automatically. The output video’s dimension (height and width) in this strategy is the same as requested, and the aspect ratio is preserved. This is accomplished by resizing the video to the requested dimension and then cropping extra parts to get desired height & width.
URL – https://ik.imagekit.io/demo/sample-video.mp4?tr=w-400,h-200
Notice that the video’s dimension matches 400×200, but the content is cropped from all edges, i.e., by default, ImageKit will extract the video from the center. You can change this behavior using the focus parameter.
Fit inside the container (no cropping)
If you want the image to fit inside the requested height & width container, use c-at_max.
In this case, full video content is preserved, i.e., no cropping happens, the aspect ratio is maintained, but the resulting height & width might differ from what is requested. Let’s see how.
The output video is less than or equal to the dimensions specified in the URL, i.e., at least one dimension will exactly match the output dimension requested, and the other dimension will be equal to or smaller than the corresponding output dimension requested. This ensures that the output video fits nicely inside the requested height & width container.
It is equivalent to object-fit:contain or background-size:contain CSS properties.
URL – https://ik.imagekit.io/demo/sample-video.mp4?tr=w-200,h-200,c-at_max
Notice that the aspect ratio is maintained, and there is no cropping. But the height is reduced so that the video fits within a 200×200 container.
Fill container (no cropping)
If you want the video to cover the whole container, use c-at_least. The entire video content is preserved, i.e., no cropping, the aspect ratio is maintained, but the resulting height & width might be different from what is requested.
One of the dimensions will be the same as what is requested, while the other dimension will be equal to or larger than what is asked for.
It is roughly equivalent to object-fit:cover or background-size:cover CSS properties.
URL – https://ik.imagekit.io/demo/sample-video.mp4?tr=w-200,h-200,c-at_least
Notice that the height is 200px as requested, but the width is more than 200px. The aspect ratio is maintained, and there is no cropping.
No cropping – add padding around the image.
If you don’t want the video to be cropped while maintaining the aspect ratio, you can add padding around the edges to get the desired dimension. You can also control this padding’s background color to match it with your website layout and theme.
https://ik.imagekit.io/demo/sample-video.mp4?tr=w-400,h-200,cm-pad_resize,bg-F3F3F3
The video is exactly 400×200, and there is no cropping. Extra padding with background color F3F3F3 has been added to get 400×200 output dimensions.
Compress videos – Automatic video optimization
ImageKit.io offers multiple video optimization features that work out of the box. For example, automatic best format selection and quality optimization reduce the final size of the output video.
- Automatic video format conversion
- Quality optimization
Automatic video format conversion
Format optimization is the process of delivering the best video format to the end-user while taking into account various factors such as requesting device capabilities, browser support for certain video formats, and your preferences. Ensuring the right format helps you reduce the size of the video and, subsequently, the playback time.
MP4 using H.264 is widely supported; however, support for WebM (vp9) is limited.
ImageKit chooses between H.264 and VP9 codec and automatically delivers the video in the appropriate format based on browser support. The video URL remains the same, but the file is modified. This behavior is transparent for your users. The result is a small video file and a faster playback time.
You can turn this on with a single click, and format conversion will be automatic. That’s how simple video optimization is with ImageKit.
Video Quality optimization
There is a trade-off between visual quality and file sizes. However, it is possible to compress a video file without any loss in perceptual visual quality.
ImageKit.io allows you to choose a quality level between 1 and 100. 1 results in the lowest perceptual quality and smallest file size. 100 results in the highest perceptual quality and biggest file size.
You can set a default video quality once, and all videos will be compressed using this value.
Remove audio from silent videos
With the audio codec (ac) parameter, you can remove the audio channel from the video file. This is going to optimize your videos and make them lighter.
Set ac-none in the URL like this:
https://ik.imagekit.io/demo/sample-video.mp4?tr=ac-none
Conclusion
Well, that’s it. We have covered an exhaustive list of techniques to master video optimization on the web. If you have stayed till the end, it means you are serious about optimizing videos on your website.
ImageKit has been empowering 700+ companies and more than 60,000 developers across the globe in handling their media.
It’s your turn now; Sign-up for a forever free account with ImageKit and start optimizing your media today!
The post Video optimization for the web simplified with ImageKit appeared first on Codrops.