Form an image from received bytes from server and display that image into the picturebox

N

nishi.hirve

Hello,

I am writing 1 client-server application in which I have written my
server in C on linux system and client in C#.

My server is sending image bytes of that image size to the client.
After receiving image bytes on client side, I want to form an image
from received bytes and want to display that image onto the picture-box
control.

Server Code:
-------------------
FILE *fp;
char buf[1024];
fp = fopen("./line.jpg","rb");

if(!stat(fileName,&file))
printf("File Size : %d\n",file.st_size);

while(!feof(fp))
{
bytesRead = fread(buf, 1, file.st_size, fp);

sent = sendto(sock, buf, bytesRead, 0,
(struct sockaddr *)&from, fromlen);

}

Client code:
-----------------
Socket sockVar;
byte[] tmpBuf = new byte[size];
MemoryStream streamImage = null;

recv = sockVar.ReceiveFrom(tmpBuf, 0, size, SocketFlags.None,
RemoteEndPoint);

streamImage = new MemoryStream(tmpBuf, true);
streamImage.Write(tmpBuf, 0, tmpBuf.Length);

try
{
picImageBox.Image = Image.FromStream(streamImage);
streamImage.Flush();
streamImage.Close();
}
catch (Exception excp)
{
MessageBox.Show(excp.Message);
}

-----------------------------------------------------------------------------------------------------------------------------
In above code, client-server communication is properly happening and i
m able to receive all the bytes of the image into the corresponding
buffer. I m not getting any error, exception but the expected image is
not getting displayed into the picture-box. Is there any other way to
display an image?

Thanks in Advance.

Regards,
Nishi
 
J

Jon Skeet [C# MVP]

I am writing 1 client-server application in which I have written my
server in C on linux system and client in C#.

My server is sending image bytes of that image size to the client.
After receiving image bytes on client side, I want to form an image
from received bytes and want to display that image onto the picture-box
control.

Client code:
-----------------
Socket sockVar;
byte[] tmpBuf = new byte[size];
MemoryStream streamImage = null;

recv = sockVar.ReceiveFrom(tmpBuf, 0, size, SocketFlags.None,
RemoteEndPoint);

You need to make sure you've read the whole thing - you're unlikely to
get it from one call.
streamImage = new MemoryStream(tmpBuf, true);
streamImage.Write(tmpBuf, 0, tmpBuf.Length);

When you've written this, you should rewind the stream - set the
Position to 0.
try
{
picImageBox.Image = Image.FromStream(streamImage);
streamImage.Flush();
streamImage.Close();
}
catch (Exception excp)
{
MessageBox.Show(excp.Message);
}

When you've used Image.FromStream, you shouldn't close the stream
afterwards - the image will do that when it is disposed.
 
Top