Image Optimization April 29, 2020 by Mikhail Kokarev

PHP Image Resizing & Optimization

Have you ever heard of PHP resizing images? Well, it can! This server-side programming language lets you manipulate picture size and quality in addition to basic features such as uploading files (e.g., with asynchronous JS). There are a few built-in methods to perform just PHP image optimization, and more functional third-party libraries and services to reduce image size via PHP with more compression settings.

PHP image optimization includes these tasks:

  • Compression (downsizing without noticeable quality loss)
  • Scaling (creating responsive web pages and optimizing traffic for different screen sizes)
  • Selecting a suitable image format automatically (JPEG, PNG, WEBP)

In this article, you’ll learn how to create a simple PHP image compressor.

Prerequisites

In order to do any compression, an image has to be delivered to a server in the first place. Read an article on asynchronous JS uploading →

Another prerequisite for PHP is installing a GD library.

When a PHP Image Optimizer Is Important

On-site PHP image optimization may be important for all sorts of web services that allow picture uploading. Here is one common use case: a web service in which you ask users to upload profile pictures. These pictures will be displayed small and they have limitations; e.g., picture size must be 100×100 px and the file size can only be up to 200 KB.

Most people have unoptimized photos from their 10+ megapixel cameras which are way larger than these requirements. Some people don’t know how to crop and resize images, or they use a phone, not a computer, so there are no tools to do it precisely. At this point, some users might abandon your website and never come back. Therefore, it’s necessary to make picture optimization automatic so users don’t need to bother about all that technical stuff.

Optimize Images and Save Traffic

Optimized images save a lot of traffic, increase loading speed, and improve your website’s key metrics.

Check out PageDetox and see what amount of compression and other optimization measures can be applied to your website. For example, here I pulled up page loading analytics for a large retail store with 55 million monthly visits.

Key Customer Experience insights for website loading. It says 22 images were analyzed, Page weight is 1.17 MB (with 63% of images) and page loading time is 25.37 sec. The graph suggests 42% faster loading with Adaptive Delivery by Uploadcare.

For this particular page, image optimization will make loading 42% faster. Hence, it’ll provide a better retention rate and an increased average shopping cart amount for each customer within one shopping session.

PHP imagejpeg() Сompression

The first PHP method to apply is a standard imagejpeg() function. It works with already uploaded pictures and it either saves the output as a .jpeg file or shows it in a browser. An image must be located on your server or on another domain to which you have access.

The syntax is as follows:

imagejpeg ( resource $image, int $to, int $quality ) : Bool

  • $image: Specify an image resource.
  • $to (Optional): The path to save the processed file. Use NULL to show in a browser and still apply quality.
  • $quality (Optional): The .jpeg quality setting.

The quality range is 1 to 100. The less quality, the more compression is applied, and the value 0 applies no compression. The recommended value is 75 and higher..

Before we apply the imagejpeg() function, we need to load a resource image from its source location using imagecreatefromjpeg(). Here is an example of a script that displays a compressed JPEG in a browser window:

<?php 
// Create an image resource
$im = imagecreatefromjpeg('https://yourdomain.com/testimage.jpg'); 

// Add an HTML header and specify the MIME type of the image to display
header('Content-type: image/jpg');

// Decrease the quality of the image to 75
imagejpeg($im, NULL, 75);
imagedestroy($im);
?>

Instead of displaying the picture in the browser, you can create compressed versions of images, put them in a separate folder, and show them as needed. Put the path img/compressed75 instead of the second parameter, which is NULL.

This method may consume a lot of storage, so we recommend adaptive delivery, which compresses an image to whatever format, quality, and size is needed, depending on the visitor’s device, Internet connection speed, and many other parameters.

There are adjacent methods for other image types such as imagepng(), etc.

Also, imagejpeg() may be used for generating images (e.g., from text or vector information). This can be used to create watermarks and other elements.

Read more in the official php.net documentation →

For more sophisticated compression and image manipulation, such as filters, check out the native PHP extension imagick.

Third-party Image Optimization Libraries

There are a couple of open source PHP libraries that can be used for image optimization:

Image Optimizer by Piotr Sliwa. It works with .png, .jpg and .gif images, and is very straightforward to use. The library also utilizes other tools such as optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim, and jpegtran.

PHP Image Cache by nielse63. This is a PHP class that allows you to optimize, process and cache the most common image formats, which are .png, .jpg, and .gif.

Uploadcare PHP Image Compression

Uploadcare provides a PHP interface to handle image compression. However, it uses another technology at its core, which is based on one of the most efficient Python open-source libraries, Pillow-SIMD.

Read the Uploadcare PHP installation steps at the GitHub page.

You’ll need PHP 5.3+, Curl, JSON and Composer version 2.

Step 1

Define your Uploadcare public and secret API keys.

define('UC_PUBLIC_KEY', 'demopublickey');
define('UC_SECRET_KEY', 'demosecretkey');

You’ll obtain your public key from the target project in your Uploadcare admin panel.

Retrieving a public key from Uploadcare

Step 2

After that, you need to include the following file and use the \Uploadcare namespace,

require_once 'vendor/autoload.php';
use \Uploadcare;

Step 3

Create an Uploadcare API object to access methods
$api = new Uploadcare\Api(UC_PUBLIC_KEY, UC_SECRET_KEY);

After that, you can access all Uploadcare methods via $api.

Refer to the REST API documentation for more information on PHP image optimization methods.

Compression accessible from HTML

While REST API can be used in your PHP application, you can change the image quality with Uploadcare right in HTML by simply altering the src link:

<img src="//ucarecdn.com/:uuid/:operations/-/quality/lighter/"/>

This is the easiest way to  change the compression:

-/quality/:value/

These operations are non-destructive, so your original images will stay intact.

The :value can be 

  • lighter — compress images without quality loss. ≈80% file size.
  • lightest — good parameter for retina displays and ultra-high resolutions. ≈50% file size.
  • smart — automatic content-aware mode to compress images.

Other parameters and progressive loading in detail →

Summary of PHP Compression and Optimization

Standard PHP functions have all the basic tools to do simple compression. Third-party open source libraries are quite advanced, with more controls such as on-the-fly compression, filters, watermarks, etc.

Uploadcare provides PHP access to compression mechanisms and much more, such as file uploading and delivery handling. It’s a complete solution for managing all the pictures on your website.

Need an easier way to optimize images?

Leave a comment

*

*