C# 获取Image图片格式
Posted 代码描绘人生
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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图片格式的主要内容,如果未能解决你的问题,请参考以下文章