2

I'm trying to implement two PHP functions to disable image resizing for gif images on WordPress that are animated. There's a solution to disable the upload if the file MIME type is gif, but this isn't enough. A gif can also be just a image. So I thought I combine it with a PHP script that checks if a file is an animated gif or not by using this solution. This seems to work if I lets say echo this function on my theme file, but doesn't seem to function if I use it inside functions.php.

/**
* Detects animated GIF from given file pointer resource or filename.
*
* @param resource|string $file File pointer resource or filename
* @return bool
*/
function is_animated_gif($file)
{
    $fp = null;

    if (is_string($file)) {
        $fp = fopen($file, "rb");
    } else {
        $fp = $file;

        /* Make sure that we are at the beginning of the file */
        fseek($fp, 0);
    }

    if (fread($fp, 3) !== "GIF") {
        fclose($fp);

        return false;
    }

    $frames = 0;

    while (!feof($fp) && $frames < 2) {
        if (fread($fp, 1) === "\x00") {
            /* Some of the animated GIFs do not contain graphic control extension (starts with 21 f9) */
            if (fread($fp, 1) === "\x21" || fread($fp, 2) === "\x21\xf9") {
                $frames++;
            }
        }
    }

    fclose($fp);

    return $frames > 1;
}

function disable_upload_sizes( $sizes, $metadata ) {

  $uploads = wp_upload_dir();
  $upload_path = $uploads['baseurl'];
  $relative_path = $metadata['file'];
  $file_url = $upload_path . $relative_path;

  if( is_animated_gif( $file_url ) ) {
    $sizes = array();
  }

  // Return sizes you want to create from image (None if image is gif.)
  return $sizes;
}   
add_filter('intermediate_image_sizes_advanced', 'disable_upload_sizes', 10, 2);

What am I'm doing wrong over here that this isn't functioning?

r1987
  • 507
  • 1
  • 7
  • 21
  • add `or` condition for gif as well in this line: `if (fread($fp, 3) !== "GIF") {` – Jigar Shah Jun 21 '17 at 07:14
  • Hmm… but I only want to filter out filetype gif that is animated, why add an or condition and what would it be? – r1987 Jun 21 '17 at 07:21
  • I meant `if (fread($fp, 3) !== "GIF" || fread($fp, 3) !== "gif") {` – Jigar Shah Jun 21 '17 at 07:23
  • This doesn't seem to make a difference. It still doesn't ignore regenerating image sizes for animated gif files. – r1987 Jun 21 '17 at 07:46
  • I'm not sure but it looks like the order the filters are being added matters, so WordPress could be adding another filter later or sooner, could you check this? – ebob Jun 26 '17 at 18:23
  • `echo this function on my theme file` what do you mean by this ? – tinker Jun 26 '17 at 21:44

1 Answers1

3

your code works... but there's an error on the $file_url.

It should be $file_url = $upload_path . '/' . $relative_path;

Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139