Send image to server as binary data

后端 未结 2 1932
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 10:58

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 ser

相关标签:
2条回答
  • 2020-11-30 11:08

    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];
     }
    
    0 讨论(0)
  • 2020-11-30 11:14

    Use the drawrect method to do signatures on an UIImage. For that you have to use a UITouch delegate

    and use the following to convert your UIImage object to NSData

    // 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);
    
    0 讨论(0)
提交回复
热议问题