Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress image interlace filter
<?php
/**
* This workaround append interlaced (aka progressive) on images
* https://korrekt.ch/
* We salute you ;)
*/
add_filter('wp_generate_attachment_metadata', 'korrekt_wp_generate_attachment_metadata', 99, 2);
function korrekt_wp_generate_attachment_metadata($metadata, $attachment_id)
{
if (!function_exists('imageinterlace'))
{
return $metadata;
}
$image = get_post($attachment_id);
$image_metadata = $metadata;
if ($image && isset($image_metadata['file']))
{
$interlace_jpg = apply_filters('attachment_interlace_jpg', true);
$interlace_png = apply_filters('attachment_interlace_png', false);
$interlace_gif = apply_filters('attachment_interlace_gif', false);
if (!$interlace_jpg && !$interlace_png && !$interlace_gif) {
return $metadata;
}
$source_dir = dirname(get_attached_file($image->ID, true));
$image_sizes_excludes = apply_filters('attachment_interlace_size_excludes', array(
'full'
));
foreach ($image_metadata['sizes'] as $size => $data)
{
$source_attributes = wp_get_attachment_image_src($image->ID, $size);
$source_name = basename($data['file']);
$source_mimetype = (string)$data['mime-type'];
$source_read = $source_dir . '/' . $source_name;
if (!file_exists($source_read) || in_array($size, $image_sizes_excludes))
{
continue;
}
switch ($source_mimetype)
{
case 'image/jpeg':
if ($interlace_jpg && $ghost = imagecreatefromjpeg($source_read))
{
imageinterlace($ghost, 1);
$image_create = imagejpeg($ghost, $source_read, apply_filters('jpeg_quality', 95, 'edit_image'));
imagedestroy($ghost);
}
break;
case 'image/png':
if ($interlace_png && $ghost = imagecreatefrompng($source_read))
{
imageinterlace($ghost, 1);
$image_create = imagepng($ghost, $source_read);
imagedestroy($ghost);
}
break;
case 'image/gif':
if ($interlace_gif && $ghost = imagecreatefromgif($source_read))
{
imageinterlace($ghost, 1);
$image_create = imagegif($ghost, $source_read);
imagedestroy($ghost);
}
break;
}
}
}
return $metadata;
}
/* Example usage of filter */
add_filter( 'attachment_interlace_jpg' , 'korrekt_attachment_interlace_jpg' );
function korrekt_attachment_interlace_jpg($state)
{
// modifiy state if necessary
// do something here ...
if ( $state === false ) {
$state = true;
}
return $state;
}
@batosai

This comment has been minimized.

Copy link

batosai commented Dec 22, 2016

Good filter, thank you
Imageinterlace works only for jpeg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.