2017-06-21 172 views
2

我想实现两个PHP函数来禁用图像调整大小的动画WordPress的gif图像。如果文件MIME类型为gif,则有solution禁用上载,但这还不够。 GIF也可以只是一个图像。 所以我想我把它和一个PHP脚本结合起来,通过使用这个solution来检查一个文件是否是动画gif。这似乎工作,如果我让我的主题文件回声这个功能,但似乎不起作用,如果我在functions.php中使用它。禁用图像调整大小,如果动画gif

/** 
* 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); 

我在做什么错在这里,这是不正常的?

+0

加上'为GIF或'状况以及在这一行:'如果(FREAD($ FP,3)== “GIF”!){' –

+0

嗯...但我只想过滤出动画的filetype gif,为什么要添加一个或一个条件,它会是什么? – r1987

+0

我的意思是,如果(fread($ fp,3)!==“GIF”|| fread($ fp,3)!==“gif”){' –

回答

3

您的代码有效......但在$file_url上有错误。

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