作为二进制数据发送图像到服务器
问题描述:
我想制作一个iPhone应用程序将图像发送到我的服务器。作为二进制数据发送图像到服务器
我想画一些东西在iPhone(例如:签名)作为图像POST二进制映像到我的服务器(服务器是JSP)。请告诉我我必须做什么?
- 如何使用iPhone UI?
- 如何从图像使二进制数据等
答
首先就可以得到含有或者是PNG或使用UIImagePNGRepresentation和UIImageJPEGRepresentation功能的图像数据的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];
}
答
使用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);
谢谢您的回答。 在上面的指南中,NSData是从任何地方存在的PNG/JPEG文件获得的。但我想直接在iPhone中绘制签名并从中获取NSData。我必须做什么? – MartinJoo 2010-03-02 08:55:07
如果您还希望在您的发布请求中在服务器上设置几个增值服务,该怎么办? – joshue 2010-11-20 01:48:13
这个问题差不多2年了!回答海报的原始内容和后续问题:在Yannick的回复中,您会看到“yourImage”值。该值应该表示图像的UIImage。因此,如果您在屏幕上绘制图像,并将图像截图捕获到名为“myImageView”的UIImageView中,则应通过“myImageView.image”引用该ImageView中包含的UIImage。然后UIImage将被翻译/序列化成二进制数据(使用上面的方法),它将被附加到你的URLRequest。我希望澄清事情。 :) – user298261 2012-10-04 21:04:55