将NSData [UIImage]转换为NSString [英] Convert NSData [UIImage] to a NSString

查看:74
本文介绍了将NSData [UIImage]转换为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.

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

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);

NSLog语句仅将输出生成为:

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.

亲切的问候

推荐答案

您不能仅从任意二进制数据中创建UTF-8编码的字符串-数据实际上必须是UTF-8编码的,并且该数据为您的JPEG图像显然不是.您的二进制数据不代表字符串,因此您不能直接从它创建字符串--[NSString initWithData:encoding:]在您的情况下会相应失败.

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.

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

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.

这篇关于将NSData [UIImage]转换为NSString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆