【问题标题】:Disable image resizing if animated gif如果是动画 gif,则禁用图像大小调整
【发布时间】:2017-06-21 07:12:17
【问题描述】:

我正在尝试实现两个 PHP 函数来禁用 WordPress 上动画 gif 图像的图像大小调整。如果文件 MIME 类型是 gif,则有一个 solution 来禁用上传,但这还不够。 gif 也可以只是图像。 所以我想我把它和一个 PHP 脚本结合起来,通过使用这个solution 检查文件是否是动画 gif。如果我让我在我的主题文件上回显这个函数,这似乎有效,但如果我在 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);

我在这里做错了什么,这不起作用?

【问题讨论】:

  • 在这一行添加or gif 的条件:if (fread($fp, 3) !== "GIF") {
  • 嗯……但我只想过滤掉动画的文件类型 gif,为什么要添加 or 条件,它会是什么?
  • 我的意思是if (fread($fp, 3) !== "GIF" || fread($fp, 3) !== "gif") {
  • 这似乎没有什么不同。它仍然不会忽略为动画 gif 文件重新生成图像大小。
  • 我不确定,但看起来过滤器的添加顺序很重要,所以 WordPress 可能会稍后或更快地添加另一个过滤器,你能检查一下吗?

标签: php wordpress image


【解决方案1】:

您的代码有效...但$file_url 出现错误。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-16
    • 2014-08-16
    • 2010-10-07
    • 2018-04-18
    • 2013-02-09
    • 1970-01-01
    • 2011-08-09
    • 2011-08-31
    相关资源
    最近更新 更多