How to convert image to binary format in iOS?

I am working on a project where I need to upload an image to my server. I want to store my binary image data in a BLOB data type field in a database. Therefore, I need to convert the image to binary format. So that it can be saved in the server database.

So how to convert the image to binary format? Please inform.

+4
source share
2 answers

You can use the CoreGraphics ' UIImagePNGRepresentation(UIImage *image) method, which returns an NSData and saves it. and if you want to convert it to UIImage , create it using the [UIimage imageWithData:(NSData *data)] method.

Demo of sending your UIImage to the server

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

Using:

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

As per requirement.

0
source

Source: https://habr.com/ru/post/1479338/


All Articles