Actions according to image type and size

I want to do some actions according to image type and size, but the script I’m using is kind of heavy and is skyrocketing my wait time (first byte) from 5 to even 40 seconds (usually it’s bellow a second).

$image_data = wp_get_attachment_image_src( get_post_thumbnail_id($post -> ID), 'full');

$animated = is_animated_gif($image_data[0]);
$width = $image_data[1];

if($animated){
    $size = 'full';
}
elseif(!$animated && ($width >= '558')) {
    $size = 'medium';
}else{
    $size = 'full';
}

checking animated gifs with this function

Read More
function is_animated_gif($filename){
$filecontents = file_get_contents($filename);

$str_loc = 0;
$count = 0;
while ($count < 2) { # There is no point in continuing after we find a 2nd frame

    $where1 = strpos($filecontents, "x00x21xF9x04", $str_loc);

    if ($where1 === false) {
        break;
    } else {

        $str_loc = $where1 + 1;
        $where2 = strpos($filecontents, "x00x2C", $str_loc);

        if ($where2 === false) {
            break;
        } else {
            if ($where1 + 8 == $where2) {
                $count++;
            }
            $str_loc = $where2+1;
        }

    }
}

if ($count > 1) {
    return true ;
} else {
    return false;
}
}

Do you have any ideas?

Related posts

Leave a Reply

1 comment

  1. That function looks like the kind of thing that would slow down a site. 🙂

    The first thing I’d recommend is that you not run that function on the front end. Run it when the image is uploaded and store the result in the database using wp_update_attachment_metadata. You can then retrieve the data with wp_get_attachment_metadata. An administrator/editor can swallow a 40 second lag. Your readers shouldn’t have to.

    If you have a huge number of images and can’t loop over them to alter the metadata so you have to run that function on image display, save the data with wp_update_attachment_metadata anyway so that it only has to run once.

    Secondly, I would use get_post_mime_type at the top of that function and exit if the attachment isn’t a GIF. Only a GIF can be an animated GIF right?