Cloudinary Blog

Compressing, Resizing, and Optimizing PHP Images

Compressing, Resizing, and Optimizing PHP Images

Image optimization, which results in the smallest possible file size but no loss in visual quality, is a mandatory step before delivery. That way, you save bytes and improve website performance because the smaller the image files, the faster the browser can download and render them on viewers’ screens.

Currently, web developers build apps in many programming languages, such as PHP, Python, and Ruby. This article shows you how to optimize images in PHP, one of the most common server-side languages for building web apps.


How to Optimize for Page-Load Speed


The Importance of Image Optimization

The faster images load on your website, the more likely visitors will return, yielding higher conversion rates. In fact, half of all visitors expect websites to load within two seconds. Surveys from Akamai and Gomez have revealed that—

  • Lengthy load time is a major contributing factor of page abandonment, which becomes more likely with each additional second of load time. Nearly 40 percent of visitors abandon a page after only three seconds.
  • Seventy-three percent of mobile users have experienced problems with load times on their devices.
  • A one-second delay in load time can cut visitor satisfaction by 16 percent, leading to a seven-percent-or-higher drop in conversion rate.

Image Optimization in PHP

You can optimize images in PHP in one of the following ways:

  • Through PHP’s built-in functions, such as imagejpeg(), which takes the path of the output image and quality specification between 1 and 100. As a prerequisite, install the PHP’s GD Graphics Library.
  • Through the PHP Image Optimizer, a PHP library built by Piotr Sliwa, which leverages several libraries, including OptiPNG, pngquant, and [jpegoptim](http://jpegclub.org/jpegtran/). The Image Optimizer can compress image files by 10-70 percent without sacrificing visual appeal.
  • With the PHP Image Cache, a simple PHP class that compresses images on the fly. Once PHP Image compression is complete, the Image Cache caches the image in your browser and then returns the image’s new source.
  • With Imagick, a native PHP extension for creating and modifying images by means of the ImageMagick API.

An Ideal Alternative for Optimizing Images in PHP

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 images are seamlessly displayed on viewers’ devices.

Cloudinary offers the following optimization capabilities:

  • Automatic quality adjustment and encoding: Once you have added the q_auto parameter to an image URL, Cloudinary chooses the optimal quality-compression level and encoding settings according to the image content, its format, and the viewing browser. The result is a compressed image with superior visual quality. See this example:

    Ruby:
    Copy to clipboard
    cl_image_tag("woman.jpg", :quality=>"auto")
    PHP:
    Copy to clipboard
    cl_image_tag("woman.jpg", array("quality"=>"auto"))
    Python:
    Copy to clipboard
    CloudinaryImage("woman.jpg").image(quality="auto")
    Node.js:
    Copy to clipboard
    cloudinary.image("woman.jpg", {quality: "auto"})
    Java:
    Copy to clipboard
    cloudinary.url().transformation(new Transformation().quality("auto")).imageTag("woman.jpg");
    JS:
    Copy to clipboard
    cloudinary.imageTag('woman.jpg', {quality: "auto"}).toHtml();
    jQuery:
    Copy to clipboard
    $.cloudinary.image("woman.jpg", {quality: "auto"})
    React:
    Copy to clipboard
    <Image publicId="woman.jpg" >
      <Transformation quality="auto" />
    </Image>
    Vue.js:
    Copy to clipboard
    <cld-image publicId="woman.jpg" >
      <cld-transformation quality="auto" />
    </cld-image>
    Angular:
    Copy to clipboard
    <cl-image public-id="woman.jpg" >
      <cl-transformation quality="auto">
      </cl-transformation>
    </cl-image>
    .Net:
    Copy to clipboard
    cloudinary.Api.UrlImgUp.Transform(new Transformation().Quality("auto")).BuildImageTag("woman.jpg")
    Android:
    Copy to clipboard
    MediaManager.get().url().transformation(new Transformation().quality("auto")).generate("woman.jpg");
    iOS:
    Copy to clipboard
    imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setQuality("auto")).generate("woman.jpg")!, cloudinary: cloudinary)
    https://res.cloudinary.com/demo/image/upload/q_auto/woman.jpg

    To fine-tune the visual quality of your images through automation, add the q_auto:best. q_auto:low, q_auto:good, or q_auto:eco parameter, as you desire.

  • Automatic formatting: Adding the f_auto parameter to image URLs causes Cloudinary to optimally format images. In most cases, Chrome users would receive a WebP (.webp); Internet Explorer users, a JPEG-XR (.jxr); and Safari users, a JPEG 2000 (.jp2). If a browser does not support any of those formats, Cloudinary deliversthe image in the format depicted by the file extension.

    In case you add both the f_auto and q_auto parameters to the URL of a JPEG image, Cloudinary’s automated quality algorithm halts chroma subsampling, retaining the JPEG format with no switch to WebP. That’s a quality safeguard because the lossy WebP format always performs chroma subsampling, which might reduce the visual quality of some images.

  • Resizing and cropping: By adding the width (w) and height (h) parameters to their URLs, you can resize images with Cloudinary, as in this example:

    Ruby:
    Copy to clipboard
    cl_image_tag("sample.jpg", :width=>0.5, :crop=>"scale")
    PHP:
    Copy to clipboard
    cl_image_tag("sample.jpg", array("width"=>0.5, "crop"=>"scale"))
    Python:
    Copy to clipboard
    CloudinaryImage("sample.jpg").image(width=0.5, crop="scale")
    Node.js:
    Copy to clipboard
    cloudinary.image("sample.jpg", {width: "0.5", crop: "scale"})
    Java:
    Copy to clipboard
    cloudinary.url().transformation(new Transformation().width(0.5).crop("scale")).imageTag("sample.jpg");
    JS:
    Copy to clipboard
    cloudinary.imageTag('sample.jpg', {width: "0.5", crop: "scale"}).toHtml();
    jQuery:
    Copy to clipboard
    $.cloudinary.image("sample.jpg", {width: "0.5", crop: "scale"})
    React:
    Copy to clipboard
    <Image publicId="sample.jpg" >
      <Transformation width="0.5" crop="scale" />
    </Image>
    Vue.js:
    Copy to clipboard
    <cld-image publicId="sample.jpg" >
      <cld-transformation width="0.5" crop="scale" />
    </cld-image>
    Angular:
    Copy to clipboard
    <cl-image public-id="sample.jpg" >
      <cl-transformation width="0.5" crop="scale">
      </cl-transformation>
    </cl-image>
    .Net:
    Copy to clipboard
    cloudinary.Api.UrlImgUp.Transform(new Transformation().Width(0.5).Crop("scale")).BuildImageTag("sample.jpg")
    Android:
    Copy to clipboard
    MediaManager.get().url().transformation(new Transformation().width(0.5).crop("scale")).generate("sample.jpg");
    iOS:
    Copy to clipboard
    imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setWidth(0.5).setCrop("scale")).generate("sample.jpg")!, cloudinary: cloudinary)
    Flower
    Ruby:
    Copy to clipboard
    cl_image_tag("sample.jpg", :height=>200, :crop=>"scale")
    PHP:
    Copy to clipboard
    cl_image_tag("sample.jpg", array("height"=>200, "crop"=>"scale"))
    Python:
    Copy to clipboard
    CloudinaryImage("sample.jpg").image(height=200, crop="scale")
    Node.js:
    Copy to clipboard
    cloudinary.image("sample.jpg", {height: 200, crop: "scale"})
    Java:
    Copy to clipboard
    cloudinary.url().transformation(new Transformation().height(200).crop("scale")).imageTag("sample.jpg");
    JS:
    Copy to clipboard
    cloudinary.imageTag('sample.jpg', {height: 200, crop: "scale"}).toHtml();
    jQuery:
    Copy to clipboard
    $.cloudinary.image("sample.jpg", {height: 200, crop: "scale"})
    React:
    Copy to clipboard
    <Image publicId="sample.jpg" >
      <Transformation height="200" crop="scale" />
    </Image>
    Vue.js:
    Copy to clipboard
    <cld-image publicId="sample.jpg" >
      <cld-transformation height="200" crop="scale" />
    </cld-image>
    Angular:
    Copy to clipboard
    <cl-image public-id="sample.jpg" >
      <cl-transformation height="200" crop="scale">
      </cl-transformation>
    </cl-image>
    .Net:
    Copy to clipboard
    cloudinary.Api.UrlImgUp.Transform(new Transformation().Height(200).Crop("scale")).BuildImageTag("sample.jpg")
    Android:
    Copy to clipboard
    MediaManager.get().url().transformation(new Transformation().height(200).crop("scale")).generate("sample.jpg");
    iOS:
    Copy to clipboard
    imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setHeight(200).setCrop("scale")).generate("sample.jpg")!, cloudinary: cloudinary)
    Flower

Here, Cloudinary maintains the aspect ratio but resizes the image to the height and width you specified.

Ruby:
Copy to clipboard
cl_image_tag("sample.jpg", :width=>200, :height=>100, :crop=>"scale")
PHP:
Copy to clipboard
cl_image_tag("sample.jpg", array("width"=>200, "height"=>100, "crop"=>"scale"))
Python:
Copy to clipboard
CloudinaryImage("sample.jpg").image(width=200, height=100, crop="scale")
Node.js:
Copy to clipboard
cloudinary.image("sample.jpg", {width: 200, height: 100, crop: "scale"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().width(200).height(100).crop("scale")).imageTag("sample.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('sample.jpg', {width: 200, height: 100, crop: "scale"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("sample.jpg", {width: 200, height: 100, crop: "scale"})
React:
Copy to clipboard
<Image publicId="sample.jpg" >
  <Transformation width="200" height="100" crop="scale" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="sample.jpg" >
  <cld-transformation width="200" height="100" crop="scale" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="sample.jpg" >
  <cl-transformation width="200" height="100" crop="scale">
  </cl-transformation>
</cl-image>
.Net:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Width(200).Height(100).Crop("scale")).BuildImageTag("sample.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().width(200).height(100).crop("scale")).generate("sample.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setWidth(200).setHeight(100).setCrop("scale")).generate("sample.jpg")!, cloudinary: cloudinary)
Flower

Cloudinary supports many image-cropping modes: scale, fit, mfit, fill, lfill, limit, pad, lpad, mpad, crop, thumb, imagga_crop, and imagga_scale.

Conclusion

Properly optimizing and caching images is a crucial step for enhancing website performance. The tips this post offers are just a start. See the Cloudinary documentation for more ideas on optimization of JPEG images without compromising quality and on image transformations.


Want to Learn More About Image Optimization?

Recent Blog Posts

New Learning Pathways From the Cloudinary Academy

In December 2019, Cloudinary launched its customer education platform, the Cloudinary Academy, replete with courses taught by the company’s experts on developer-oriented products and digital asset management (DAM) solution. The courses comprise interactive lessons and hands-on assignments, a proven way of familiarizing the audience with the course material and illustrating it with live examples.

Read more
Maya Shavin: How I Built My Website

Besides working as a senior front-end developer at Cloudinary, I'm also a content creator, a blogger, and an open-source developer. Follow me at @mayashavin and on mayashavin.com.

In the beginning, my website, mayashavin.com, was mainly for showcasing the status of my development projects and keeping me organized with my speaking schedule. Initially, I built it with Vue.js, later on switching to Nuxt.js (aka Nuxt) for a higher SEO score, and deployed it with Netlify. After some time, I added a blog section with Netlify CMS as the content management system (CMS). Everything was fine until I added more content and features, which led to a significant decline in the site’s performance. Also, the site design needed a modern look. So, I gave the site a makeover.

Read more
Automation Frees Up PetRescue’s Staff to Help Pets Find Their Forever Homes

As we spend more time at home, many of us are adopting pets for the joy, companionship and a surprising range of health benefits. In Australia, where our nonprofit customer PetRescue is located, there’s a shortage of pets to adopt. Last August, the Guardian reported that dog shelters in Australia emptied and adoption fees for puppies were running as high as $AUS1800.

Read more
Cloudinary and Contentful Make Modern Content Management Easier

I am pleased to share that Cloudinary and Contentful have joined forces to further streamline the creation, processing, and delivery of online content through Cloudinary’s digital asset management (DAM) solution and advanced transformation and delivery capabilities for images and video. What’s more, the partnership delivers a headless approach to DAM. By leveraging APIs for media management tasks, marketers and developers alike benefit from an integrated stack of optimized assets for optimization and automation. As a result, page loads are fast and beautiful, and at scale—with less overhead and effort.

Read more
Introducing Cloudinary's Nuxt Module

Since its initial release in October 2016 by the Chopin brothers as a server-side framework that runs on top of Vue.js, Nuxt (aka Nuxt.js) has gained prominence in both intuitiveness and performance. The framework offers numerous built-in features based on a modular architecture, bringing ease and simplicity to web development. Not surprisingly, Nuxt.js has seen remarkable growth in adoption by the developer community along with accolades galore. At this writing, Nuxt has earned over 30K stars on GitHub and 96 active modules with over a million downloads per month. And the upward trend is ongoing.

Read more