4

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

So How to convert an image into binary format? Please advise.

5
  • 5
    Use the CoreGraphics' method UIImagePNGRepresentation(UIImage *image), which returns NSData and save it this way. Commented May 6, 2013 at 10:33
  • 1
    Thanks @BuntyMadan But it doesn't convert image in binary format. Commented May 6, 2013 at 10:34
  • But You can send the NSData raw data to the server and then convert it into UIImage. Commented May 6, 2013 at 10:36
  • 2
    What do you mean by binary format? Commented May 6, 2013 at 10:47
  • Yeah, define "binary format". Everything on the phone is binary. Commented May 6, 2013 at 11:11

2 Answers 2

12

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

Demo to send your UIImage to 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) {
       }
       [request release];
 }
Sign up to request clarification or add additional context in comments.

1 Comment

May you provide a Swift example of just the first two lines (before code block)? I'm trying it and it's not working.
0

Use:

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

According to requirement.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.