将图像作为二进制数据发送到服

时间:2010-02-24 04:42:46

标签: iphone

我想创建一个iPhone应用程序来将图像发送到我的服务器。

我想在iPhone中绘制一些东西(例如:签名)作为图像,将二进制图像POST到我的服务器(服务器是JSP)。请告诉我我该做什么?

  • 如何使用iPhone UI?
  • 如何从图像等制作二进制数据

2 个答案:

答案 0 :(得分:12)

首先,您可以使用UIImagePNGRepresentation和UIImageJPEGRepresentation函数获取包含图像数据的PNG或JPEG表示的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);

(有关详细信息,请参阅:UIImage Class Reference

要完成将数据从iPhone上传到服务器,您可以执行以下操作:

- (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];
 }

答案 1 :(得分:0)

使用drawrect方法在UIImage上进行签名。为此,您必须使用UITouch代理

并使用以下内容将您的UIImage对象转换为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);