8

我制作了这段代码来接收图像并将其转换为位图图像,但它不起作用。

这是代码:

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);

并给我这个错误:

参数无效

4

4 回答 4

9

这是另一种方法

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);
于 2013-04-30T12:55:52.747 回答
1

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

请参阅:Stream.Read 方法的返回值

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

PS:我假设lengths 和reads 是拼写错误。

于 2012-07-30T22:21:27.947 回答
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;
                    }
                }
于 2012-07-30T22:20:59.230 回答
-1

尝试这个:

int size = BitConverter.ToInt32(data.Reverse().ToArray(),0); 
于 2012-07-30T22:20:46.233 回答