如何在 C# 中读取 .img 文件

How to read .img file in C#

我正在开发一个 Windows 表单应用程序,我需要做的其中一件事是从 .img 文件中提取图像。我可以读取普通的 jpg 和 png 文件,但不能读取 .img 文件。

我在互联网上找不到太多关于此的信息。我确实在 msdn 上找到了一些代码,我试图让它工作。下面是抛出的代码和异常。

 FileInfo file = new FileInfo(FilePath.Text);
 FileStream f1 = new FileStream(FilePath.Text, FileMode.Open, 
 FileAccess.Read, FileShare.Read);
 byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
 f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));

 MemoryStream mStream = new MemoryStream();
 mStream.Write(BytesOfPic, 0, Convert.ToInt32(BytesOfPic.Length));
 Bitmap bm = new Bitmap(mStream, false);
 mStream.Dispose();

 // ImageBox is name of a PictureBox
 ImageBox.image = bm;   // this line is throwing the error

捕获异常

System.ArgumentException: Parameter is not valid. at System.Drawing.Bitmap..ctor(Stream stream, Boolean useIcm) at A02_Stegnography.Form1.ReadImgFile() in C:\Users\tiwar\Desktop\A02-Stegnography\A02-Stegnography\Form1.cs:line 65

如果这是一个愚蠢的问题,我很抱歉。我希望我提供了足够的信息,但如果我没有提供,请告诉我。

FileInfo file = new FileInfo(FilePath.Text);
FileStream f1 = new FileStream(FilePath.Text, FileMode.Open, 
FileAccess.Read, FileShare.Read);
byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));

using (MemoryStream mStream = new MemoryStream())
{
    mStream.Write(BytesOfPic, 0, BytesOfPic.Length);
    mStream.Seek(0, SeekOrigin.Begin);
    Bitmap bm = new Bitmap(mStream);

    // ImageBox is name of a PictureBox
    ImageBox.image = bm;
}

你可以试试我的解决方案