2010-04-30 45 views
0

我已經接管了以前的開發人員在我的工作中創建的自定義論壇的工作,並且遇到了一個小錯誤。我們不允許在論壇中將動畫GIF作爲頭像。但是,如果有人要拍攝動畫GIF,請將其重命名爲imagename.jpeg,然後上傳,論壇將顯示圖像爲動畫。ASP.NET:如何檢查圖像是否爲GIF,特別是帶有更改擴展名的圖像

這是一個非常奇怪的錯誤,因爲如果擴展名不是.gif,我甚至不認爲它播放了動畫。

所以我的問題是:有沒有辦法檢查(在.NET 2.0中)如果圖像是動畫gif,即使擴展名不是?

巴拉

回答

0

下面是PHP的一小部分(從PHP論壇中獲取),它完全符合您的需求。將它轉換爲.NET應該非常簡單。

function is_animated_gif($filename) 
{ 
    $filecontents=file_get_contents($filename); 

    $str_loc=0; 
    $count=0; 
    while ($count < 2) 
    { 
      $where1=strpos($filecontents,"\x00\x21\xF9\x04",$str_loc); 
      if ($where1 === FALSE) 
      { 
        break; 
      } 
      else 
      { 
        $str_loc=$where1+1; 
        $where2=strpos($filecontents,"\x00\x2C",$str_loc); 
        if ($where2 === FALSE) 
        { 
          break; 
        } 
        else 
        { 
          if ($where1+8 == $where2) 
          { 
            $count++; 
          } 
          $str_loc=$where2+1; 
        } 
      } 
    } 

    if ($count > 1) 
    { 
      return(true); 
    } 
    else 
    { 
      return(false); 
    } 
} 
0

爲了方便起見,這裏是轉化爲工作的C#代碼的PHP代碼:

byte[] byteCode1 = { 0x00, 0x21, 0xF9, 0x04 }; 
byte[] byteCode2 = { 0x00, 0x2C }; 
String strTemp; 
byte[] byteContents; 
bool bIsAnimatedGif = false; 
int iCount; 
int iPos = 0; 
int iPos1; 
int iPos2; 
Stream st = null; 

// st is a stream previously opened on a file 
byteContents = new byte[st.Length]; 
st.Read(byteContents, 0, (int)st.Length); 
strTemp = System.Text.Encoding.ASCII.GetString(byteContents); 
byteContents = null; 
iCount = 0; 
while (iCount < 2) 
{ 
    iPos1 = strTemp.IndexOf(System.Text.Encoding.ASCII.GetString(byteCode1), iPos); 
    if (iPos1 == -1) break; 
    iPos = iPos1 + 1; 
    iPos2 = strTemp.IndexOf(System.Text.Encoding.ASCII.GetString(byteCode2), iPos); 
    if (iPos2 == -1) break; 
    if ((iPos1 + 8) == iPos2) 
     iCount++; 
    iPos = iPos2 + 1; 
} 
if (iCount > 1) bIsAnimatedGif = true; 
0

來檢測,如果圖像文件是在ASP.NET動態GIF的最好辦法是通過.NET API本身。這裏是VB.NET示例代碼:

Imports System.Drawing 
Imports System.Drawing.Imaging 

Public Class ImageHelper 

    Shared Function IsAnimatedGif(filepath As String) As Boolean 
     Return GetFrameCount(filepath) > 1 
    End Function 

    Shared Function GetFrameCount(filepath As String) As Integer 
     Using bitmap As New Bitmap(filepath) 
      Dim dimensions As New FrameDimension(bitmap.FrameDimensionsList(0)) 
      Return bitmap.GetFrameCount(dimensions) 
     End Using 
    End Function 

End Class 

同一樣品用C#:

using System.Drawing; 
using System.Drawing.Imaging; 

public class ImageHelper 
{ 
    public static bool IsAnimatedGif(string filepath) 
    { 
     return GetFrameCount(filepath) > 1; 
    } 

    public static int GetFrameCount(string filepath) 
    { 
     using (Bitmap bitmap = new Bitmap(filepath)) 
     { 
      FrameDimension dimensions = new FrameDimension(bitmap.FrameDimensionsList[0]); 
      return bitmap.GetFrameCount(dimensions); 
     } 
    } 
}