The client program sends pictures to the server

Source: Internet
Author: User

Reprint: http://www.cnblogs.com/networkcomms/p/4314898.html

Source (because the space size limit, does not contain the communication framework source code, the communication framework source code, please download separately)

Used to help a friend to do a picture acquisition system, the client after collecting photos, through the TCP communication to the server, this article to the client to send pictures to the server this part of the extraction.

Since the size of each picture is not large, so we transfer the picture, not the way to transfer files, but the use of direct serialization of the image of the way to do.

Currently supported picture types: jpg,png,gif You can add your own expanded supported image types

The communication framework uses the UK Open source networkcomms2.3.1 Communication Framework serializer using open source Protobuf.net

Let's start with a look at the effect of the implementation

Server-side:

Client:

On the server side, we save the received image in the D packing directory (you can specify the path), open D to see the picture received as follows:

Let's take a look at the specific process

The first step is to set up the server side first

(1) Listening port:

     int. Parse (Txtport.text));               false);            " in listening "false;      

(2) for image upload write corresponding processing method:

Networkcomms.appendglobalincomingpackethandler<imagewrapper> ("uploadimage", incominguploadimage);  
  //Working with pictures sent by clientsPrivatevoidIncominguploadimage (packetheader header, Connection Connection, Imagewrapper wrapper) {Try{//Specific parsing work is done by the communication framework//Get the picture file and picture name from the picture wrapper image image =Wrapper. Image;String fileName =Wrapper. ImageName;//Get file name extensionint index = Filename.lastindexof (‘.‘);String extion =Filename.substring (Index +1, Filename.length-index-1); Extion =Extion. ToLower ();//Set 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 specified a save path, and you can customize the image. Save (@ "d:\" + FileName, imageformat); Resmsgcontract contract = new Resmsgcontract (); Contract. Message =  " upload succeeded " ; // send reply message to client connection. SendObject ( "resuploadimage  "catch (Exception ex) {}}      

Step two: Setting up the client

(1) Connect the server:

assigns a value int to the connection information object            . Parse (Txtport.text));            // if unsuccessful, the exception message pops up newtcpconnection =false" connection succeeded ";        

(2) Select images from local and upload them

Openfiledialog1.filter ="Picture files |*.jpg| All files |*.*";if (openfiledialog1.showdialog () = =DialogResult.OK) {String ShortFileName =System.IO.Path.GetFileName (Openfiledialog1.filename);//Picture wrapper class Imagewrapper wrapper =NewImagewrapper (ShortFileName, Image.FromFile (openfiledialog1.filename));//Send the picture wrapper class to the server and get the return information resmsgcontract resmessage = newtcpconnection.sendreceiveobject<resmsgcontract> ("uploadimage" resuploadimage8000 if (Resmessage.message = =  upload successful  ") { MessageBox.Show ( " picture has been uploaded to the server  ");} else {MessageBox.Show (  " Picture was not sent successfully " ); } }  

(iii) about the Imagewrapper category

In the process of client-to-server communication, we notice that the above program uses a Imagewrapper class to pass a picture object.

The Imagewrapper class, which is stored in the MessageContract class library, is used to serialize the picture

We know that the image class does not directly support serialization, so the way we do this is to convert the image to two-level data before serializing, and then convert the two-level data into an image class before deserializing it.

We are only responsible for defining the Imagewrapper class, and the other working communication framework helps us do it.

  UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Text;UsingProtobuf;UsingSystem.Drawing;UsingSystem.IO;UsingProtobuf;Namespacemessagecontract{[Protocontract]PublicClassImagewrapper {///<summary>///Storing an Image object as a private byte array///</summary> [Protomember (1)]PrivateByte[] _imagedata;///<summary>///Picture name///</summary> [Protomember (2)]PublicString ImageName {GetSet; }///<summary>///Picture Object///</summary>Public image Image {GetSet; }///<summary>///Private parameterless constructors need to be deserialized using the///</summary>PrivateImagewrapper () {}///<summary>///Create a new Imagewrapper class///</summary>///<param name= "ImageName" ></param>///<param name= "image" ></param>Public Imagewrapper (StringImageName, image image) {This. ImageName =ImageName;This. Image =Image }///<summary>///Convert a picture to binary data before serializing///</summary>[Protobeforeserialization]PrivatevoidSerialize () {if (Image! =Null) {//We need to decide how to convert our image to its raw binary form hereusing (MemoryStream InputStream =NewMemoryStream ()) {//For basic image types The features is part of the. NET FrameworkImage.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 by networkcomms.net//e.g. see dpsmanager.getdataprocessor<lzmacompressor> ()//Store the binary image data as bytes[] _imagedata =Inputstream.toarray (); } } }///<summary>///Convert binary data to a picture object when deserializing///</summary> [Protoafterdeserialization] private void deserialize () {MemoryStream ms = new MemoryStream (_imagedata); //if we added custom data processes We have the perform the R Everse operations here before //trying to recreate the Image object //e.g. dpsmanager.getdataprocessor< Lzmacompressor> ()  Image = Image.fromstream (ms); _ ImageData = null     
Imagewrapper

Work to this completion, very little code volume, help us to achieve the delivery client picture saved in the server function.

Note: This method is not suitable for the transmission of larger pictures, if the picture is larger, such as more than 10M, it is best to transfer files in the form of sections sent.

The client program sends pictures to the server

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.