如何在iOS中将图像转换为二进制格式?

我正在一个项目,我需要上传图像到我的服务器。 我想将我的图像的二进制数据存储到数据库中的BLOB数据types字段。 所以我需要将我的图像转换成二进制格式。 这样它可以保存在服务器数据库上。

那么如何将图像转换为二进制格式? 请指教。

你可以使用CoreGraphics的方法UIImagePNGRepresentation(UIImage *image) ,它返回NSData并保存它。 如果你想再次转换成UIImage使用[UIimage imageWithData:(NSData *data)]方法创build它。

演示将您的UIImage发送到服务器

 - (void)sendImageToServer { UIImage *yourImage= [UIImage imageNamed:@"image.png"]; NSData *imageData = UIImagePNGRepresentation(yourImage); NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]]; // Init 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:imageData]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection) { // response data of the request } [request release]; } 

使用:

 NSData *data = UIImageJPEGRepresentation(image, 1.0); //OR NSData *data = UIImagePNGRepresentation(image); 

根据要求。