2011-03-12 27 views
7

我试图在c#中将byte[]转换为Bitmap。以下是代码:从c#中的字节[]创建图像时,参数无效错误#

MemoryStream ms = new MemoryStream(b); 
Bitmap bmp = new Bitmap(ms); 

它创建Bitmap时显示错误Parameter is not valid

byte[] b来自网络流。

但是,当我把这个byte []写到一个文件中,并且在任何图像查看器中打开这个文件都是完美的。以下是将字节[]写入文件的代码:

var fs = new BinaryWriter(new FileStream("tmp.bmp", FileMode.Create, FileAccess.Write)); 
fs.Write(b); 
fs.Close(); 

我在这里丢失了什么?

编辑

这里是我的,是造成问题

Socket s = listener.AcceptSocket(); 
byte[] b = new byte[imgLen]; 
s.Receive(b); 
MemoryStream ms = new MemoryStream(b); 
// now here I am using ms.Seek(0, SeekOrigin.Begin); that fixed my problem. 
Bitmap bmp = new Bitmap(ms); 
pictureBox1.Image = bmp; 
s.Close(); 

我使用事件的代码并没有什么额外的全部代码。我只是试图显示在网络上传输的图像。服务器是使用Java编写的,它正在流式传输此映像。

希望它澄清疑惑。

感谢

+0

您是否尝试过使用Image.FromStream代替?我想不出为什么这可能会奏效,但值得一试...... – 2011-03-12 20:19:46

+1

试过Image.FromStream,但那也没有奏效。 – 2011-03-12 20:23:44

+0

@Jon Jon,Darin本周就有你了! – 2011-03-12 20:24:44

回答

5

尝试流

MemoryStream ms = new MemoryStream(b); 
ms.Seek(0, SeekOrigin.Begin); 
Bitmap bmp = new Bitmap(ms); 
+0

这是我第一次想到的,但是当你直接从字节数组构造一个MemoryStream时,没有必要这样做。 – 2011-03-12 20:27:35

+0

谢谢!我从过去2小时开始伸展脑袋,并用谷歌搜索,但没有找到任何解决方案。你是伟人!再次感谢:) – 2011-03-12 20:30:16

+0

因此,显然,毕竟还是有需要的,或者有代码参与,我们没有看到;)。 – Abel 2011-03-12 20:32:43

0

尝试这样的:

byte[] b = ... 
using (var ms = new MemoryStream(b)) 
using (var bmp = Image.FromStream(ms)) 
{ 
    // do something with the bitmap 
} 
+0

首先,我会使用Image.FromStream而不是Bitmap.FromStream(因为它在Image中定义,而不是在Bitmap中定义),其次我无法看到这会如何影响* constructor *工作与否。 – 2011-03-12 20:26:44

+2

这也给我同样的错误! – 2011-03-12 20:26:49

+0

@Vinod Maurya,我刚刚测试了这个代码,让'b = File.ReadAllBytes(“test.png”);'它成功地加载到位图中。 @Jon,你对“Image”是正确的。 – 2011-03-12 20:30:12

13

奥凯在重置当前的位置,只是为了澄清事情有点......问题是,new Bitmap(ms)将从流的当前位置读取数据 - 如果流当前位于的数据,它不会读取任何东西,因此问题。

问题声称的代码是这样的:

MemoryStream ms = new MemoryStream(b); 
Bitmap bmp = new Bitmap(ms); 

在这种情况下,存在没有要求重置流的位置,因为这将是0已经。不过,我怀疑的代码是实际上更是这样的:

MemoryStream ms = new MemoryStream(); 
// Copy data into ms here, e.g. reading from NetworkStream 
Bitmap bmp = new Bitmap(ms); 

或可能:

MemoryStream ms = new MemoryStream(b); 
// Other code which *reads* from ms, which will change its position, 
// before we finally call the constructor: 
Bitmap bmp = new Bitmap(ms); 

在这种情况下,你需要重新设置位置,因为否则的“光标”的流是在的数据而不是开始。就我个人而言,我更喜欢使用Position财产,而不是Seek方法,只是为了简单起见,所以我会用:

MemoryStream ms = new MemoryStream(); 
// Copy data into ms here, e.g. reading from NetworkStream 

// Rewind the stream ready for reading 
ms.Position = 0; 
Bitmap bmp = new Bitmap(ms); 

它只是表明它是多么的重要,在一个问题的示例代码代表实际代码...

+0

我正在使用'MemoryStream ms = new MemoryStream(b);'来创建内存流! – 2011-03-12 21:05:17

+0

@Vinod:那么在调用位图构造函数之前,您必须先使用它来*做其他事情......因为这样构建的流的初始位置*为0 *。如果你可以发布* full *代码,我们可以进一步帮助...但我不相信你正在为一个字节数组创建'MemoryStream',然后立即调用'新的Bitmap(ms)'。如果你是,倒退简直*无助*。 – 2011-03-12 21:12:05

+0

你写'//其他代码*从ms读*,这会改变它的位置。这不是我第一次看到人们逐步调试,用鼠标悬停,调用getter,调用副作用。或使用立即窗口。这是一个完美的例子,其副作用可能会导致只能在调试环境中运行(抛出)的行为。 – Abel 2011-03-12 21:19:25

相关问题