[C # source sharing] client program to send pictures to the server

Source: Internet
Author: User

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:

     New int . Parse (Txtport.text));                false );             " Listening in " ;             false;

(2) for image upload write corresponding processing method:

Networkcomms.appendglobalincomingpackethandler<imagewrapper> ("uploadimage" , Incominguploadimage);
  //working with pictures sent by clients        Private voidIncominguploadimage (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 wrapperImage image =Wrapper.                Image; stringFileName =Wrapper.                             ImageName; //get file name extension                intindex = Filename.lastindexof ('.'); stringExtion =filename.substring (Index+1, Filename.length-index-1); Extion=extion.                ToLower (); //Set file FormatImageFormat 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, and you can customize the image. Save (@"D:\"+FileName, ImageFormat); Resmsgcontract Contract=Newresmsgcontract (); Contract. Message="Upload Successful"; //send reply message to clientConnection. SendObject ("Resuploadimage", contract); } Catch(Exception ex) {}}

Step two: Setting up the client

(1) Connect the server:

// Assigning a value            to a connection information object New int . Parse (Txtport.text));             // if not successful, the exception message            pops up Newtcpconnection = tcpconnection.getconnection (conninfo);            Tcpconnection.startlistening (conninfo.localendpoint);             false ;             " Connection Successful ";

(2) Select images from local and upload them

Openfiledialog1.filter ="picture files |*.jpg| All files |*.*"; if(Openfiledialog1.showdialog () = =DialogResult.OK) {stringShortFileName =System.IO.Path.GetFileName (openfiledialog1.filename); //picture Packing classImagewrapper wrapper =NewImagewrapper (ShortFileName, Image.FromFile (openfiledialog1.filename)); //send a picture wrapper class to the server and get the return informationResmsgcontract resmessage = newtcpconnection.sendreceiveobject<resmsgcontract> ("Uploadimage","Resuploadimage",8000, wrapper); if(Resmessage.message = ="Upload Successful") {MessageBox.Show ("the picture has been uploaded to the server"); }                Else{MessageBox.Show ("picture 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] Public classImagewrapper {/// <summary>      ///storing an Image object as a private byte array/// </summary>[Protomember (1)]      Private byte[] _imagedata; /// <summary>      ///Picture name/// </summary>[Protomember (2)]       Public stringImageName {Get;Set; } /// <summary>       ///Picture Object/// </summary>       PublicImage Image {Get;Set; } /// <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>       PublicImagewrapper (stringImageName, image image) {           This. ImageName =ImageName;  This. Image =image; }         /// <summary>      ///convert a picture to binary data before serializing/// </summary>[Protobeforeserialization]Private voidSerialize () {if(Image! =NULL)          {              //We need to decide how to convert our image to its raw binary form here              using(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 voidDeserialize () {MemoryStream ms=NewMemoryStream (_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

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.

[C # source sharing] client program to send 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.