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;
} 该文章在 2021/3/18 12:05:43 编辑过 |
关键字查询
相关文章
正在查询... |