Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

iphone - Send image to server as binary data

I want to make an iPhone application to send an image to my server.

I want to draw something in iPhone (ex: a signature) as an image to POST binary image to my server (server is JSP). Please tell me what I have to do?

  • how to use iPhone UI?
  • how to make binary data from image, etc.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly you can get an NSData object containing either a PNG or JPEG representation of the image data using the UIImagePNGRepresentation and UIImageJPEGRepresentation functions.

// To get the data from a PNG file
NSData *dataForPNGFile = UIImagePNGRepresentation(yourImage);

// To get the data from a JPEG file
NSData *dataForPNGFile = UIImageJPEGRepresentation(yourImage, 0.9f);

(for more information see: UIImage Class Reference)

To finish to upload data from your iPhone to your server you can do this:

- (void)sendImage {
       NSData *postData = [nsdata from your original image];
       NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

       // Init and set fields of the URLRequest
       NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
       [request setHTTPMethod:@"POST"];
       [request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]];
       [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
       [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
       [request setHTTPBody:postData];

       NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
       if (connection) {
          // Return data of the request
          NSData *receivedData = [[NSMutableData data] retain];
       }
       [request release];
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...