I am developing a C# .NET application which will display the image captured from a camera (smart camera). I am using the function below to convert the raw data received from the camera (which is a byte array) to a bitmap image. The problem I face with the below code is that, the image displayed in the C# .NET application's picture box (which should be a live image ideally) looks like a movie reel and it keeps scrolling to the right. Any idea how to solve this issue?
private Image ByteArrayToImage(byte[] myByteArray)
{
if (myByteArray != null)
{
MemoryStream ms = new MemoryStream(myByteArray);
int Height = 504; /*The exact height of image from Smart Camera*/
int Width = 664; /*The exact width of image from Smart Camera*/
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
Marshal.Copy(myByteArray, 0, bmpData.Scan0, myByteArray.Length);
Bitmap bmp = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, bmp.PixelFormat);
int offset = 0;
long ptr = bmpData.Scan0.ToInt64();
for (int i = 0; i < Height; i++)
{
Marshal.Copy(myByteArray, offset, new IntPtr(ptr), Width);
offset += (Width);
ptr += bmpData.Stride;
}
bmp.UnlockBits(bmpData);
return bmp;
}
return null;
}
@Mark, find below the code segment i use for receiving data from camera ...
Logic : I receive the sizeof image first and then open socket connection n loop till i get the sizeof bytes from the camera.
public static byte[] receivedata(Socket clientSock)
{
if (clientSock != null)
{
byte[] size = new byte[10000000];
byte[] buffer = null;
int ch, received, offset;
try
{
clientSock.Receive(size);
//MessageBox.Show("size array is " + size[0] + " " + size[1] + " " + size[2] + " " );
ch = BitConverter.ToInt32(size, 0);
//ch = 334656;
//MessageBox.Show("Sizeofimg = " + ch + "");
buffer = new byte[ch];
//MessageBox.Show("Start receiving image from camera");
received = 0;
offset = 0;
do
{
received += clientSock.Receive(buffer, offset + received, ch - received, SocketFlags.None);
} while (received < ch);
//MessageBox.Show("Received " + received + " values");
System.Threading.Thread.Sleep(50);
}
catch (Exception e)
{
MessageBox.Show("Error receiving ...");
MessageBox.Show(e.StackTrace);
}
return buffer;
}
else
{
return null;
}
}
}
Kindly point out the problem ... Thanks in advance.