2012-07-30 108 views
4

我让这段代码接收图像并将其转换为位图图像,但它不起作用。字节数组到位图图像

下面是代码:

public void ReceiveImage() 
{ 
    NetworkStream stream = new NetworkStream(socket); 
    byte[] data = new byte[4]; 
    stream.read(data,0,data.length,0) 
    int size = BitConverter.ToInt32(data,0); 
    data = new byte[size]; 
    stream.read(data,0,data.length) 
    MemoryStream imagestream = new MemoryStream(data); 
    Bitmap bmp = new Bitmap(imagestream); 
    picturebox1.Image = bmp; 
} 

它得到:

Bitmap bmp = new Bitmap(imagestream); 

,给我这个错误:

Parameter is not valid

+0

@Tarek ...这是C#代码?当我将它复制到Visual Studio中时,它有一些错别字。 – MikeTWebb 2012-07-30 22:11:56

+0

是它的C#,但是你必须使用System.IO键入 ;使用System.Net.Sockets的 ;使用System.Net的 ; – 2012-07-30 22:14:11

+0

并且还使用System.Drawing.Imaging; – 2012-07-30 22:16:29

回答

-1

试试这个:

int size = BitConverter.ToInt32(data.Reverse().ToArray(),0); 
+6

'试试这个'只是一个评论。 '试试这个。这应该工作,因为......是一个答案。 – 2012-07-30 22:48:33

0

我假设你有一个表,并希望从数据库接收图片。

int cout = ds.Tables["TableName"].Rows.Count; 
       if (cout > 0) 
       { 
        if (ds.Tables["TableName"].Rows[cout - 1]["Image"] != DBNull.Value) 
        { 
         var data = (byte[])(ds.Tables["TableName"].Rows[cout - 1]["Image"]); 
         var stream = new MemoryStream(data); 
         pictureBox1.Image = Image.FromStream(stream); 
        } 
        else 
        { 
         pictureBox1.Image = null; 
        } 
       } 
+1

你的假设可能是错误的。请参阅代码'NetworkStream' – 2012-07-30 22:26:47

1

你可能不stream.read(data,0,data.length)因为Read接收到足够的字节数并不能保证它会读data.length字节。您必须检查其返回值并继续读取,直到读取data.Length字节。

参见:Stream.Read Method的返回值

int read = 0; 
while (read != data.Length) 
{ 
    read += stream.Read(data, read, data.Length - read); 
} 

PS:我假设length S和read s为错别字。

+0

发生此错误 '无法从传输连接读取数据。可以执行套接字上的操作,因为系统缺少足够的缓冲空间或者队列已满。 – 2012-07-30 23:01:25

+0

检查'尺寸'。它可以[网络字节顺序](http://betterexplained.com/articles/understanding-big-and-little-endian-byte-order/)。你可以尝试'IPAddress.NetworkToHostOrder(BitConverter.ToInt32(data,0))' – 2012-07-30 23:06:27

+0

不工作,来'data = new byte [size];' 然后给我这个错误 '算术运算导致溢出' – 2012-07-30 23:26:02

7

这是一种替代方法

int w= 100; 
int h = 200; 
int ch = 3; //number of channels (ie. assuming 24 bit RGB in this case) 

byte[] imageData = new byte[w*h*ch]; //you image data here 
Bitmap bitmap  = new Bitmap(w,h,PixelFormat.Format24bppRgb); 
BitmapData bmData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); 
IntPtr pNative  = bmData.Scan0; 
Marshal.Copy(imageData,0,pNative,w*h*ch); 
bitmap.UnlockBits(bmData); 
+0

使用此代码,我应该包括什么? – 2015-08-13 16:34:55

+1

感谢我的工作 – predactor 2017-05-13 23:51:44