Convert NSData [UIImage] to a NSString

假装没事ソ 提交于 2019-12-10 12:00:45

问题


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.



来源:https://stackoverflow.com/questions/1815635/convert-nsdata-uiimage-to-a-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!