Tips / Examples on sending an Image file (jpeg, png) over socket programming?

前端 未结 2 1284
深忆病人
深忆病人 2021-01-21 12:44

I\'ve heard that we can somehow send an image file with binary over a socket... But I have no idea on how to convert an image file into binary or how to even think of sending it

相关标签:
2条回答
  • 2021-01-21 13:06

    Any image files you have are already binary. You can just send them over the socket.

    0 讨论(0)
  • 2021-01-21 13:07

    You will need to know, or have the user tell you, a path that will find the image file.

    Once you have that, then you logically open the file, read it into a buffer, and then write that buffer over the socket, and finally close the file (always close what you open and free what you allocate). However, there are details to be sorted - like how does the receiving end know that the data that follows is an image and how big it is (so it knows when you've sent it all). Your protocol will, presumably, define a bit pattern (one or two bytes) that identifies the message as an image, and then probably use four bytes to specify the size of the image, followed by the correct number of bytes. You can find the size of a file using the POSIX-based stat() system call. Alternatively, you can send a series of packets containing parts of the image (again with a type - this time, of type 'image packet' instead of 'image') plus the length of the packet (which might only be a 16-bit unsigned integer, for a maximum size of 65535 bytes), plus an 'end image packet' for the last segment. This is perhaps easier for the sender; it is easy for the receiver if the data goes direct to file, but messy if the receiver needs the image in memory.

    0 讨论(0)
提交回复
热议问题