我使用此代码接收图像并将其转换为位图图像,但它不起作用。
以下是代码:
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);
并且给了我这个错误:
参数无效
答案 0 :(得分:8)
这是一种替代方法
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);
答案 1 :(得分: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
和read
是拼写错误。
答案 2 :(得分: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;
}
}
答案 3 :(得分:-1)
试试这个:
int size = BitConverter.ToInt32(data.Reverse().ToArray(),0);