Convert NSData [UIImage] to a NSString

2019-06-09 23:17发布

问题:

I am aware this question has been asked several times, but I was unable to find a definate answer that would best fit my situation.

I want the ability to have the user select an image from the library, and then that image is converted to an NSData type. I then have a requirement to call a .NET C# webservice via a HTTP get so ideally I need the resulting string to be UTF8 encoded.

This is what I have so far:

NSData *dataObj = UIImageJPEGRepresentation(selectedImage, 1.0);
    [picker dismissModalViewControllerAnimated:YES];
    NSString *content =  [[NSString alloc] initWithData:dataObj encoding:NSUTF8StringEncoding];
    NSLog(@"%@", content);

The NSLog statement simply produces output as:

2009-11-29 14:13:33.937 TestUpload2[5735:207] (null)

Obviously this isnt what I hoped to achieve, so any help would be great.

Kind Regards

回答1:

You can't create a UTF-8 encoded string out of just any arbitrary binary data - the data needs to actually be UTF-8 encoded, and the data for your JPEG image obviously is not. Your binary data doesn't represent a string, so you can't directly create a string from it - -[NSString initWithData:encoding:] fails appropriately in your case.

Assuming you're using NSURLConnection (although a similar statement should be true for other methods), you'll construct your NSMutableURLRequest and use -setHTTPBody: which you need to pass an NSData object to. I don't understand why you would be using a GET method here since it sounds like you're going to be uploading this image data to your web service - you should be using POST.