怎么判断当前的 Bitmap 是否一张有效的图片?

marklr 2016-10-21 01:59:40
我是连续从摄像机接收每一帧,但有时候 Bitmap 赋值到picturebox 会出现 红叉 错误,所以我想先判断当前接收到的 Bitmap 是否具备正确的图片格式后再发送到指定的 Picturebox。
...全文
820 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
圣殿骑士18 2016-10-21
  • 打赏
  • 举报
回复

public string CheckImage(string fileName)
        {
            FileStream fs = null;
            BinaryReader reader = null;
            Image image = null;

            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                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();

                //255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar   
                List<string> list = new List<string>() { "255216", "7173", "6677", "13780" };
                if (list.Contains(fileClass))
                {
                    image = Image.FromFile(fileName);
                }
                else
                {
                    return "非图片文件,无法打开!";
                }
            }
            catch (Exception ex)
            {
                return "图片打开失败,可能格式存在问题:" + ex.Message;
            }
            finally
            {
                if (image != null) image.Dispose();
                reader.Close();
                fs.Close();
            }

            return "success";
        }
marklr 2016-10-21
  • 打赏
  • 举报
回复
没人?我这分要打水漂了?

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧