惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
MyScale Blog
MyScale Blog
博客园 - Franky
酷 壳 – CoolShell
酷 壳 – CoolShell
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
雷峰网
雷峰网
罗磊的独立博客
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
The Cloudflare Blog
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
博客园 - 司徒正美
Last Week in AI
Last Week in AI
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
宝玉的分享
宝玉的分享

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Why I Wrote a Pixel-by-Pixel Multiply Blend in PHP-GD to ...
Joshua · 2026-04-28 · via DEV Community

A real estate broker came to me with a familiar problem. Every property exposé — the glossy multi-page PDF that goes to potential buyers — was being assembled by hand in an Adobe layout tool. Address typed in. Prices typed in. Photos imported one by one. Floor plans appended. Logo placed. Disclaimer pasted. PDF exported. Filed somewhere. Sent.

That's 45 minutes per listing. And the moment a price changes, you're starting over.

The agency was already on WordPress. JetEngine was already managing properties as custom post types. So the path was clear: generate the exposé directly from the data — one click, one PDF, pixel-perfect corporate design.

The first 80% of that plugin was straightforward. PHP, Dompdf, an HTML template, FPDI to merge in the floor plan PDFs. Done in a week.

The last 20% almost killed me.

The Dompdf opacity problem

The cover page of an exposé is one of those classic real-estate looks: a hero photo of the property, with a dark gradient overlay so the headline is legible.

In CSS, that's three lines:

.cover {
    background-image: url(...);
    background-blend-mode: multiply;
}
.overlay {
    opacity: 0.6;
    background: linear-gradient(...);
}

Enter fullscreen mode Exit fullscreen mode

In Dompdf, both background-blend-mode and opacity are unreliable. They render inconsistently between Dompdf versions, between fonts, between paper sizes. I spent three hours coaxing different combinations before accepting that this isn't going to work.

The obvious move would be to swap libraries. mPDF? wkhtmltopdf? Browserless?

But all of those add operational weight: wkhtmltopdf is a binary that needs to be installed and updated on the host. Browserless is an external service. mPDF would mean rewriting the templating layer.

The agency wanted something they could deploy on standard WordPress hosting. No binaries. No external services. No black boxes.

So I went the other way.

Pre-compute the blend in PHP-GD

If Dompdf can't blend at render time, the blend has to happen before Dompdf sees the image. Which means doing it in PHP, with GD, pixel by pixel.

// Multiply-blend two images of the same size
function multiply_blend($base, $overlay) {
    $width  = imagesx($base);
    $height = imagesy($base);

    for ($y = 0; $y < $height; $y++) {
        for ($x = 0; $x < $width; $x++) {
            $b = imagecolorat($base, $x, $y);
            $o = imagecolorat($overlay, $x, $y);

            // Multiply formula per channel: (a × b) / 255
            $r = (($b >> 16 & 0xFF) * ($o >> 16 & 0xFF)) / 255;
            $g = (($b >> 8  & 0xFF) * ($o >> 8  & 0xFF)) / 255;
            $bl = (($b      & 0xFF) * ($o      & 0xFF)) / 255;

            $color = imagecolorallocate($base, $r, $g, $bl);
            imagesetpixel($base, $x, $y, $color);
        }
    }
    return $base;
}

Enter fullscreen mode Exit fullscreen mode

That's brute-force math, twice the resolution times two channels per pixel. On a 1600×900 cover image, that's roughly 1.4 million iterations per blend. Slow.

Then you encode the result as JPEG with high quality and embed it as a base64 data-URI directly in the HTML that goes into Dompdf:

ob_start();
imagejpeg($blended, null, 92);
$encoded = base64_encode(ob_get_clean());
$dataUri = "data:image/jpeg;base64,{$encoded}";

Enter fullscreen mode Exit fullscreen mode

Dompdf doesn't know it's looking at a blended image. It just sees <img src="data:image/jpeg;..."> and embeds the bytes. Pixel-perfect output.

The cache makes it fast

Brute-force blending is fine if you don't do it often. The plugin generates each PDF once, then caches it in wp-content/uploads/. It only re-renders when the underlying data changes — and it knows that via a hash:

function inex_get_or_generate_pdf($post_id) {
    $cached_version  = get_post_meta($post_id, '_inex_pdf_cache_version', true);
    $current_version = inex_get_cache_version($post_id);

    if (file_exists($filepath) && hash_equals($cached_version, $current_version)) {
        return $fileurl; // Serve from cache, sub-second
    }

    if (!inex_acquire_pdf_generation_lock($post_id)) {
        return new WP_Error('locked', 'PDF being generated, please retry');
    }

    try {
        $data = inex_collect_expose_data($post_id);
        inex_render_expose_pdf_file($data, $filepath . '.tmp');
        rename($filepath . '.tmp', $filepath); // atomic
        update_post_meta($post_id, '_inex_pdf_cache_version', $current_version);
    } finally {
        inex_release_pdf_generation_lock($post_id);
    }
}

Enter fullscreen mode Exit fullscreen mode

Three things worth flagging in this snippet:

  1. hash_equals for the cache check — not strictly security-critical here, but it sets the right habit. Same function that protects token comparison.
  2. rename on a .tmp file is atomic on POSIX filesystems. A concurrent reader never sees a half-written PDF.
  3. try/finally for the lock release. If rendering throws, the lock still clears. No "stuck PDFs" after a failed deploy.

The cache version is computed by hashing every relevant meta field plus the modification times of the gallery images. Change the price → hash changes → next download regenerates. Nobody pushes a "refresh" button. Nobody runs a cron job.

When does this approach make sense?

A custom PHP-GD blend plus Dompdf isn't elegant. It's a workaround stacked on a workaround. Six hundred lines of plugin code do the work that one CSS rule would have done if Dompdf supported it.

But it ships in a single PHP plugin. No binaries. No external dependencies. No vendor lock-in. Standard WordPress hosting handles it. Cold render: 5–15 seconds. Cached read: under one second.

The lesson, for me, was that "swap the library" isn't always the right reflex. Sometimes the cheapest path forward is a precomputation stage in your own stack that hides the limitation from the layer that has it.

You can read the full case study (German) here: hafenpixel.de/hinter-den-kulissen/expose-generator-jetengine-wordpress

Or the English version: hafenpixel.de/en/behind-the-scenes/expose-generator-jetengine-wordpress