简体   繁体   English

将NSData [UIImage]转换为NSString

[英]Convert NSData [UIImage] to a NSString

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. 我希望能够让用户从库中选择一个图像,然后将该图像转换为NSData类型。 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. 然后,我需要通过HTTP get调用.NET C#Web服务,因此理想情况下,我需要将生成的字符串进行UTF8编码。

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: NSLog语句仅产生如下输出:

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 亲切的问候

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. 您不能仅从任意二进制数据中创建UTF-8编码的字符串-数据实际上需要进行UTF-8编码,而JPEG图像的数据显然不是。 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. 您的二进制数据不代表字符串,因此您不能直接从它创建一个字符串-[NSString initWithData:encoding:]在您的情况下会失败。

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. 假设您使用的是NSURLConnection(尽管其他方法也应使用类似的语句),但您将构造NSMutableURLRequest并使用-setHTTPBody: ,您需要将NSData对象传递给该方法。 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. 我不明白为什么要在这里使用GET方法,因为这听起来像是要将图像数据上传到Web服务-您应该使用POST。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM