根據圖片流信息確定圖片類型

從網絡上下載圖片信息時經常會遇到這樣的URL

http://c.csdnimg.cn/jifen/images/xunzhang/xunzhang/chizhiyiheng.png可以很順利的得到圖片的路徑及圖片名稱

如果是這樣的URL

http://letter5.vip.com/img/7D08DA0907A3DBDF57A08A7A384AB7EED91D8587

我們就無法得到其名稱,只能通過圖片文件數據來得到其類型

Stream stream=response.Content.ReadAsStreamAsync().Result
byte[] b=new byte[4];
stream.Read(b,0,b.Length);
string type=ToHexString(b).ToUpper();   //轉大寫
string  hexType=string.Empty;
if (type.contains("FFD8FF")) {  
            hexType="jpg";  
        } else if (type.contains("89504E47")) {  
            hexType= "png";  
        } else if (type.contains("47494638")) {  
           hexType= "gif";  
        } else if (type.contains("49492A00")) {  
           hexType= "tif";  
        } else if (type.contains("424D")) {  
            hexType= "bmp";  
        }  

public static string ToHexString(byte[] bytes
{
  string hexString =string.Empty;
 StringBuilder sb=new StringBuilder();
 for(int i=0;i<bytes.Length;i++)
 {
  sb.Append(bytes[i].ToString("X2"));
 }
hexString =sb.ToString();
return hexString;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章