2017-06-21 77 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;