C# send image over HTTP

martinyyyy picture martinyyyy · Nov 11, 2010 · Viewed 13.4k times · Source

I have a small HTTP-Server here written in C# and until now I only needed to send raw text back to the sender. But now I have to send a JPG-Image and I dont unterstand how.

this is what I have now:

// Read the HTTP Request
Byte[] bReceive = new Byte[MAXBUFFERSIZE];
int i = socket.Receive(bReceive, bReceive.Length, 0);

//Convert Byte to String
string sBuffer = Encoding.ASCII.GetString(bReceive);

// Look for HTTP request
iStartPos = sBuffer.IndexOf("HTTP", 1);

// Extract the Command without GET_/ at the beginning and _HTTP at the end
sRequest = sBuffer.Substring(5, iStartPos - 1 - 5);
String answer = handleRequest(sRequest);


// Send the response
socket.Send(Encoding.UTF8.GetBytes(answer));

I think I have to do some kind of filestream instead of a string but I really have no glue..

Answer

Arsen Mkrtchyan picture Arsen Mkrtchyan · Nov 11, 2010

Do you want to send from file or Bitmap object?

MemoryStream myMemoryStream = new MemoryStream();
myImage.Save(myMemoryStream);
myMemoryStream.Position = 0;

EDIT

// Send the response
SendVarData(socket,memoryStream.ToArray());

for sending MemoryStream by socket you can use this method given here

 private static int SendVarData(Socket s, byte[] data)
 {
            int total = 0;
            int size = data.Length;
            int dataleft = size;
            int sent;

            byte[] datasize = new byte[4];
            datasize = BitConverter.GetBytes(size);
            sent = s.Send(datasize);

            while (total < size)
            {
                sent = s.Send(data, total, dataleft, SocketFlags.None);
                total += sent;
                dataleft -= sent;
            }
            return total;
 }