字节数组到位图图像

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

代码如下:

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

并给我这个错误:

参数无效


这是一种替代方法

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

您可能没有在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:我假设length s和read s是错别字。


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

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;
                    }
                }
链接地址: http://www.djcxy.com/p/75437.html

上一篇: Byte Array to Bitmap Image

下一篇: Facebook friends request returns empty