0

I created local server, that should get image files as binary data and save them back as images in hard drive.

Socket mySocket = myListener.AcceptSocket();

#region Connection Check
if (mySocket.Connected)
{
        ============
    /* Some Code For Displaying Information*/
        ============

    byte[] data = new byte[mySocket.ReceiveBufferSize];
    int i = mySocket.Receive(data, data.Length, 0);

    byteArrayToImage(data); 

    mySocket.Close();
}

byteArrayToImage method Converts byte Array to Image file and saves on hard drive, here's the code

public void byteArrayToImage(Byte[] data)
{
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    img.Save(@"C:\MyPersonalwebServer\ImageData\img.png", ImageFormat.Png);
}

but I get ArgumentException here: Image img = Image.FromStream(ms)

Here is part of data array: http://s43.radikal.ru/i101/1403/78/1913ab884790.png

Any ideas how to fix it? Thanks in advance.

w.b
  • 11,026
  • 5
  • 30
  • 49
arsena
  • 1,935
  • 19
  • 36

1 Answers1

0

The following code works for me:

var buffer = new byte[256];
FileStream fs = new FileStream(@"D:\test.png", FileMode.Open);
var ms = new MemoryStream();

int readCtr;
while ((readCtr = fs.Read(buffer, 0, buffer.Length)) > 0) 
{
    ms.Write(buffer, 0, readCtr);
}
Image img = Image.FromStream(ms);
img.Save(@"D:\test2.png", ImageFormat.Png);

Are you sure that the data you are sending from the client connection is complete/clean?

Make sure the data you are sending from the client isn't appending null bytes when performing Socket.Send(), or try clean it up server-side by stripping any null bytes from the end of the byte array:

buffer = buffer.Where(x => x != (byte)0).ToArray();

You could also check the size of the image manually against the content received server-side using standard debug practices/console output.

Either way, I dont think your code would be failing if the byte array had valid content.

DawnFreeze
  • 164
  • 1
  • 3
  • 13
  • Data was recieved from Flash application. First We tested code on string data converted in binary and back, and it worked fine. – arsena Mar 16 '14 at 05:05
  • I also checked recieved and sent data sizes and they were same. – arsena Mar 16 '14 at 05:07
  • Ok.The only time I can recreate the exception you are getting is if my byte array is not correct... if you are certain that the data retrieved from the socket connection is exactly that of the image being sent then it must be something to do with the way you are reading into your array. The max size of a byte array is 'Int32.MaxValue' ...is the image you are retrieving larger than this? – DawnFreeze Mar 16 '14 at 05:29
  • I'll recheck if image is correctly converted to binary in Flash application and reply as soon as possible. – arsena Mar 16 '14 at 05:46