Jump to content

Recommended Posts

Posted

Not really sure this is a tutorial, but if you're struggling with large PNG files, here is a nice little hook to compress them with pngquant.

Obviously you need to install pngquant (https://pngquant.org/) first and exec() can't be disabled.

$wire->addHookAfter('Pageimage::size', function(HookEvent $event) {
    $img = $event->return; // the resized Pageimage variation
    $path = $img->filename;
    
    // Only process PNGs
    if (strtolower(pathinfo($path, PATHINFO_EXTENSION)) !== 'png') return;
    
    // Skip if already optimized (optional marker file approach)
    $marker = $path . '.pngquant';
    if (file_exists($marker)) return;
    
    // Run pngquant (overwrites in place, quality 65-80)
    $cmd = sprintf(
        'pngquant --quality=65-80 --force --output %s -- %s 2>&1',
        escapeshellarg($path),
        escapeshellarg($path)
    );
    exec($cmd, $output, $returnCode);
    
    // Mark as optimized so we don't re-process on subsequent calls
    if ($returnCode === 0 || $returnCode === 99) {
        // 99 = quality target not met, kept original
        touch($marker);
    }
});

 

  • Like 4
  • Thanks 2

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...