[C # source code sharing] the client sends images to the server,

Source: Internet
Author: User

[C # source code sharing] the client sends images to the server,

Source code (because the space size is limited, the source code of the communication framework is not included. Please download the source code of the communication framework separately)

In the past, I helped a friend develop an image acquisition system. After the client collects photos, it sends them to the server through TCP communication. In this article, the client sends the images to the server for extraction.

Since the size of each image is not large, we did not use the file transfer method when transmitting the image, but directly serialized the image.

Supported image types: jpg, png, and gif

The communication framework uses the open-source networkcomms2.3.1 communication framework; the serializer uses the open-source protobuf.net

 

Let's take a look at the implementation results.

Server:

Client:

On the server side, we save the received image in the root directory of drive D (you can specify another path). Open drive D and you will see the received image as follows:

The following describes the specific process.

Step 1: first set the server

(1) listening port:

IPEndPoint thePoint = new IPEndPoint (IPAddress. parse (txtIP. text), int. parse (txtPort. text); TCPConnection. startListening (thePoint, false); button1.Text = "listening"; button1.Enabled = false;

(2) corresponding processing methods for Image Upload and writing:

 NetworkComms.AppendGlobalIncomingPacketHandler<ImageWrapper>("UploadImage", IncomingUploadImage);
// Process the image private void IncomingUploadImage (PacketHeader, Connection connection, ImageWrapper wrapper) sent from the client) {try {// The specific parsing work is completed by the communication framework. // the Image file and image name are obtained from the Image package. image = wrapper. image; string fileName = wrapper. imageName; // get the file extension int index = fileName. lastIndexOf ('. '); string extion = fileName. substring (index + 1, fileName. length-index-1); extion = extion. toLower (); // set the file format ImageFormat imageFormat = ImageFormat. bmp; switch (extion) {case "jpg": case "jpeg": imageFormat = ImageFormat. jpeg; break; case "png": imageFormat = ImageFormat. png; break; case "gif": imageFormat = ImageFormat. gif; break ;}
// Here, we manually specify a save path. You can customize the image. save (@ "D: \" + fileName, imageFormat); ResMsgContract contract = new ResMsgContract (); contract. message = "uploaded successfully"; // send the reply Message to the client connection. sendObject ("ResUploadImage", contract);} catch (Exception ex ){}}

Step 2: Set the client

(1) connect to the server:

// Assign connInfo = new ConnectionInfo (txtIP. text, int. parse (txtPort. text); // if it fails, the exception message newTcpConnection = TCPConnection will pop up. getConnection (connInfo); TCPConnection. startListening (connInfo. localEndPoint); button1.Enabled = false; button1.Text = "connection successful ";

(2) Select an image from the local device and upload it.

OpenFileDialog1.Filter = "Image File | *. jpg | all files | *. * "; if (openFileDialog1.ShowDialog () = DialogResult. OK) {string parameter filename = System. IO. path. getFileName (openFileDialog1.FileName); // Image packaging class ImageWrapper wrapper = new ImageWrapper (custom filename, Image. fromFile (openFileDialog1.FileName); // sends the image packaging class to the server and obtains the returned information ResMsgContract resMessage = newTcpConnection. sendReceiveObject <ResMsgContract> ("UploadImage", "ResUploadImage", 8000, wrapper); if (resMessage. message = "uploaded") {MessageBox. show ("image uploaded to server");} else {MessageBox. show ("the image is not sent successfully ");}}

(3) ImageWrapper class

During the communication between the client and the server, we noticed that the above program uses an ImageWrapper class to transmit Image objects.

The ImageWrapper class is stored in the MessageContract class library. This class is used to serialize images.

We know that the Image class does not directly support serialization, So we adopt the method of converting the Image into second-level data before serialization, and then converting the second-level data into the Image class before deserialization.

We are only responsible for defining the ImageWrapper class, and other work Communication frameworks help us do well.

Using System; using System. collections. generic; using System. text; using ProtoBuf; using System. drawing; using System. IO; using ProtoBuf; namespace MessageContract {[ProtoContract] public class ImageWrapper {// <summary> // stores the Image object as a private byte array /// </summary> [ProtoMember (1)] private byte [] _ imageData; // <summary> // image name // </summary> [ProtoMember (2)] public string ImageName {get; set ;} /// <summa Ry >/// Image object /// </summary> public Image {get; set ;} /// <summary> /// private non-parameter constructor used for deserialization // </summary> private ImageWrapper () {}/// <summary> /// create a new ImageWrapper class // </summary> /// <param name = "imageName"> </param>/ // <param name = "image"> </param> public ImageWrapper (string imageName, image image) {this. imageName = imageName; this. image = image;} // <summary> // before serialization, convert the Image to binary System Data // </summary> [ProtoBeforeSerialization] private void Serialize () {if (Image! = Null) {// We need to decide how to convert our image to its raw binary form here using (MemoryStream inputStream = new MemoryStream ()) {// For basic image types the features are part of. net framework Image. save (inputStream, Image. rawFormat); // If we wanted to include additional data processing here // such as compression, encryption etc we can still use the features provided NetworkComms. net // e.g. see DPSManager. getDataProcessor <LZMACompressor> () // Store the binary image data as bytes [] _ imageData = inputStream. toArray () ;}}/// <summary> /// during deserialization, convert binary data to image objects // </summary> [ProtoAfterDeserialization] private void Deserialize () {MemoryStream MS = new MemoryStream (_ imageData ); // If we added custom data processes we have the perform the reverse operations here before // trying to recreate the image object // e.g. DPSManager. getDataProcessor <LZMACompressor> () Image = Image. fromStream (MS); _ imageData = null ;}}}ImageWrapper

After the work is completed, a small amount of Code helps us implement the function of transferring client images to the server.

Note: This method is not suitable for transferring large images. If the images are large, for example, 10 MB or more, it is best to send them in the form of a file.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.