简体   繁体   English

禁用动态gif图像大小调整

[英]Disable image resizing if animated gif

I'm trying to implement two PHP functions to disable image resizing for gif images on WordPress that are animated. 我正在尝试实现两个PHP函数,以禁用WordPress上动画的gif图像的图像大小调整。 There's a solution to disable the upload if the file MIME type is gif, but this isn't enough. 如果文件的MIME类型为gif,有一种解决方案可以禁止上传,但这还不够。 A gif can also be just a image. gif也可以只是图像。 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 . 所以我想我将它与PHP脚本结合起来,通过使用此解决方案来检查文件是否为gif动画。 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. 如果我可以说在主题文件上回显此功能,则此方法似乎可行,但如果我在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? 我在这里做错了什么,这是行不通的?

your code works... but there's an error on the $file_url . 您的代码有效...但是$file_url上有错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM