简体   繁体   English

字节数组到位图图像

[英]Byte Array to Bitmap Image

I made this code to receive an image and convert it to bitmap image but it doesn't work. 我制作此代码以接收图像并将其转换为位图图像,但它不起作用。

Here is the code: 这是代码:

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

It gets to: 它得到:

Bitmap bmp = new Bitmap(imagestream);

And gives me this error: 并给我这个错误:

Parameter is not valid 参数无效

This is an alternative method 这是一种替代方法

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

You are probably not receiving enough bytes in stream.read(data,0,data.length) since Read does not ensure that it will read data.length bytes. 您可能没有在stream.read(data,0,data.length)接收到足够的字节,因为Read不能确保它将读取data.length个字节。 you have to check its return value and continue to read till data.Length bytes are read. 你必须检查它的返回值并继续读取直到data.Length字节被读取。

See : Stream.Read Method 's return value 请参阅: Stream.Read方法的返回值

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

PS: I am assuming length s and read s are typos. PS:我假设length s和read s是拼写错误。

I assume you have a table and want to receive the picture from database. 我假设你有一张桌子,想要从数据库接收图片。

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

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM