How to use Cloudflare Image Resizing with Statamic CMS

How to use Cloudflare Image Resizing with Statamic CMS

Integrate Cloudflare Images into Statamic CMS to deliver properly resized images.

Roman Zipp, July 8th, 2024

Why

Properly resizing images on web pages offers several advantages:

  • Improved Load Times: Reduces file size, leading to faster page loading and better user experience.

  • Enhanced Performance: Decreases bandwidth usage and server load.

  • SEO Benefits: Faster loading pages are favored by search engines, potentially improving rankings.

  • Mobile Optimization: Ensures images display correctly and load quickly on mobile devices.

  • Bandwidth Savings: Minimizes data consumption for users, particularly important for those on limited data plans.

  • User Experience: Avoids layout shifts and ensures images fit within the intended design.

  • Accessibility: Enhances accessibility by ensuring images are appropriately sized for screen readers and other assistive technologies.

  • Cost Efficiency: Reduces hosting and CDN costs due to smaller file sizes and reduced bandwidth usage.

Cloudflare Images

Cloudflare offers an Images product which can easily resize images hosted on their R2 storage buckets or on your own web page.

To enable CF Images, ...

  1. head over to your Cloudflare Dashboard

  2. Go to Images

  3. Select Transformations from the Sidebar

  4. Choose your Domain/Zone

  5. and click "Enable for zone"

Integrate Cloudflare Images with Statamic

Create new Tag class

php please make:tag CloudflareImageTag

Ad new file CloudflareImageTag should have been created in the folder app/Modifiers.

Tag class

namespace App\Modifiers;

use Statamic\Modifiers\Modifier;

class CloudflareImageTag extends Modifier
{
    protected static $handle = 'cf_image';

    public function index(?string $value, array $params = []): string
    {
        if ( ! $value) {
            return '';
        }

        $separator = '/';

        if (str_starts_with($value, '/')) {
            $separator = '';
        }

        $relativeUrl = sprintf('/cdn-cgi/image/%s%s%s', implode(',', $params), $separator, $value);

        if ('local' === config('app.env')) {
            return config('app.url') . $relativeUrl;
        }

        return $relativeUrl;
    }
}

Usage

To show the resized version of an image, simple attach the cf_image tag.

<img src="{{ cover | cf_image('width=600px', 'quality=90') }}"
     alt="{{ title }}"
    loading="lazy">