首页 > 代码库 > C# 获取Image图片格式
C# 获取Image图片格式
private void button1_Click_1(object sender, EventArgs e) { string path = Application.StartupPath; using (FileStream file = new FileStream(txtpath.Text, FileMode.Open)) { Image img = Image.FromStream(file); string format; System.Drawing.Imaging.ImageFormat _img_format = GetImageFormat(img, out format); if (_img_format != null) { img.Save(path + @"\" + Guid.NewGuid().ToString() + format, _img_format); MessageBox.Show("ok"); } } } /// <summary> /// 获取Image图片格式 /// </summary> /// <param name="file"></param> /// <param name="format"></param> /// <returns></returns> private System.Drawing.Imaging.ImageFormat GetImageFormat(FileStream file, out string format) { byte[] sb = new byte[2]; //这次读取的就是直接0-1的位置长度了. file.Read(sb, 0, sb.Length); //根据文件头判断 string strFlag = sb[0].ToString() + sb[1].ToString(); //察看格式类型 switch (strFlag) { //JPG格式 case"255216": format = ".jpg"; return System.Drawing.Imaging.ImageFormat.Jpeg; //GIF格式 case"7173": format = ".gif"; return System.Drawing.Imaging.ImageFormat.Gif; //BMP格式 case"6677": format = ".bmp"; return System.Drawing.Imaging.ImageFormat.Bmp; //PNG格式 case"13780": format = ".png"; return System.Drawing.Imaging.ImageFormat.Png; //其他格式 default: format = string.Empty; return null; } } /// <summary> /// 获取Image图片格式 /// </summary> /// <param name="_img"></param> /// <param name="format"></param> /// <returns></returns> private System.Drawing.Imaging.ImageFormat GetImageFormat(Image _img,out string format) { if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Jpeg)) { format = ".jpg"; return System.Drawing.Imaging.ImageFormat.Jpeg; } if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Gif)) { format = ".gif"; return System.Drawing.Imaging.ImageFormat.Gif; } if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Png)) { format = ".png"; return System.Drawing.Imaging.ImageFormat.Png; } if (_img.RawFormat.Equals(System.Drawing.Imaging.ImageFormat.Bmp)) { format = ".bmp"; return System.Drawing.Imaging.ImageFormat.Bmp; } format = string.Empty; return null; }
C# 获取Image图片格式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。