DEV Community

Cover image for Creating an Image Optimization Function in PHP🔩
Esuki
Esuki

Posted on

Creating an Image Optimization Function in PHP🔩

Like image optimization components commonly used in front-end frameworks such as Next.js and Nuxt.js, I've created a PHP function that returns an optimized image by passing an image path.

This enables the optimization of images received from external storage, CMS, etc.

Demo

https://cf785610.cloudfree.jp/index.php

The PHP version is 8.1.22.

Also use GD.

Step1: Create an API to resize and convert images to WebP

// _image.php
<?php

$url = $_REQUEST["url"];
$size["W"] = $_REQUEST["w"];

$img_data = file_get_contents($url);
$base_img = imagecreatefromstring($img_data);
list($base_w, $base_h) = getimagesizefromstring($img_data);

$zoom = $size["W"] / $base_w;
$image = imagecreatetruecolor($size["W"], $base_h * $zoom);
imagecopyresampled($image, $base_img, 0, 0, 0, 0, $size["W"], $base_h * $zoom, $base_w, $base_h);

header("Content-Type: image/webp");
header("cache-control: max-age=2592000");
imagewebp($image);

imagedestroy($base_img);
imagedestroy($image);
Enter fullscreen mode Exit fullscreen mode

We recommend restricting the origins and referers that can access this API, as well as limiting the domain of the image URL to be optimized.

Step:2 Create a function to generate an <img> tag for displaying an optimized image.

// get_optimized_image.php
<?php

function get_path($img_path = "", $size = 390)
{
  return "/_image.php?url=$img_path&w=$size " . $size . "w";
};

function get_optimized_image($attributes)
{
  $breakpoint = [390, 768, 1024, 1280, 1920]; // Feel free to adjust the breakpoint values to your preference.

  $imgs = array_map(function ($val) use ($attributes) {
    return get_path($attributes["src"], $val);
  }, $breakpoint);
  $attributes["srcset"] = implode(", ", $imgs);
?>
  <img <?php foreach ($attributes as $key => $value) {
    if ($value) {
      echo " {$key}=\"{$value}\"";
    }
  } ?> />
<?php
};
?>

Enter fullscreen mode Exit fullscreen mode

Step3: Display optimized images

// index.php
<?php
include_once('get_optimized_image.php');
?>

<body>
  <?php get_optimized_image(["src" => "https://example.com/example.jpg"]) ?>
</body>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)