Code代码片断(5do8)

GDI+控件线程IO流ADO.NET接口类,函数语法

新主题
c#获取GIF的各帧
c#验证码
c#判断文件是否是图片
说话自由

首页 » .NET/C# » GDI+ »

c#判断文件是否是图片

标签: FileStream ReadByte
读取每个文件的头两个字节, 

byte[0].ToString()+byte[1].ToString()的值 

255216:jpg,7173:gif,6677:bmp,13780:png

private bool IsPicture(string filePath)//filePath是文件的完整路径 
        {
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                BinaryReader reader = new BinaryReader(fs);
                string fileClass;
                byte buffer;
                byte[] b=new byte[2];
                buffer = reader.ReadByte();
                b[0] = buffer;
                fileClass = buffer.ToString();
                buffer = reader.ReadByte();
                b[1]=buffer;
                fileClass += buffer.ToString();


                reader.Close();
                fs.Close();
                if (fileClass == "255216 ")//255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar 
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

ccdot写于2008-9-17 13:39:29

        protected static bool IsValidGif(byte[] source)
        {
            if (source == null || source.Length < 6)
                return false;
            byte[] GIF = new byte[6];
            GIF[0] = 0x47;
            GIF[1] = 0x49;
            GIF[2] = 0x46;
            GIF[3] = 0x38;
            GIF[4] = 0x39;
            GIF[5] = 0x61;
            bool valid = true;
            int nIndex = 0;
            foreach(byte bTmp in GIF)
            {
                if(bTmp!=source[nIndex])
                {
                    valid = false;
                    break;
                }
                nIndex++;
            }
            return valid;
        }      
        protected static bool IsValidJpgOrJpeg(byte[] source)
        {
            if (source == null || source.Length < 10)
                return false;
            byte[] Jpg=new byte[4];
            Jpg[0] = 0xff;
            Jpg[1] = 0xd8;
            Jpg[2] = 0xff;
            Jpg[3] = 0xd9;

            if (source[0] == Jpg[0] && source[1] == Jpg[1] && source[source.Length - 2] == Jpg[2] && source[source.Length - 1] == Jpg[3])
                return true;
            else
                return false;
        }

ccdot 写于 2008-9-17 13:53:50#1
如果愿意,请留下你观点或者感受...
称呼*
内容*
验证码*