将UIImage转换为NSData,将NSData转换为NSString以便将图像发布到服务器

3
我有两个UIImageView。我想通过脚本将两张图片上传到服务器。在此之前,我需要把这些图片转换成数据,然后再将数据转换成字符串,但我不知道如何从UIImageView中将图像转换为NSData和NSData转换为NSString。我已经参考了所有的代码,但都无法正常工作。我还想知道应该在代码中的哪里声明转换编码(图像到数据和数据到图像)?
以下是我的实现:
.h部分
  #import <UIKit/UIKit.h>
  #import "GlobalAccessClass.h"
  #import  <QuartzCore/QuartzCore.h>

  @interface AskQuestionHome :  UIViewController<UITextViewDelegate,UITextFieldDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>

  {

  }
  @property (strong, nonatomic) IBOutlet UIImageView *imgSecondImg;

  @property (strong, nonatomic) IBOutlet UIImageView *imgFirstImg;

  @property (strong, nonatomic) IBOutlet UITextView *txtviewAsk;

  -(IBAction)postbutton:(id)sender;

  @property (nonatomic,retain) NSString *datestr;

  @property(nonatomic,retain) NSData *imageData;

  @property(nonatomic,retain) NSString *postLength;

  @end

.m part

 -(void)post
 {
     NSMutableURLRequest *mutableurlrequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://www.alvinchuastudios.com/aNSWERED/insert_question.php"]];

  // create the Method  "POST" For POSTING the QUESTIION with IMAGES
        [mutableurlrequest setHTTPMethod:@"POST"];

        NSLog(@"the email is:%@",manage.transformEmail);
        NSLog(@"the cat is:%@",manage.transformCategories);
        NSLog(@"the text is:%@",textviewText.text);
       // NSLog(@"the firstimage is:%ld",(long)imgFirstImg.tag);
       // NSLog(@"the secondimage is:%ld",(long)imgSecondImg.tag);
       // NSlog(@"the status is:%d",1);
        NSLog(@"the user is:%@",manage.transformName);
        NSLog(@"the user registered is:%@",datestr);


  //passing the string to the server
        NSString *qususerUpdate =[NSString stringWithFormat:@"email_id=%@&cat=%@&q_text=%@&q_image1=%ld&q_image2=%ld&q_status=1&last_upd_by=%@&last_upd_timestamp=%@",manage.transformEmail,manage.transformCategories,textviewText.text,(long)imgFirstImg.tag,(long)imgSecondImg.tag,manage.transformName,datestr,Nil];


  //check the value that what we passed 
        NSLog(@"the data Details is =%@", qususerUpdate);


  //Convert the String to Data
        NSData *data1 =[qususerUpdate dataUsingEncoding:NSUTF8StringEncoding];

  //Apply the data to the body
        [mutableurlrequest setHTTPBody:data1];

  //Create the response and Error
        NSError *err;
        NSURLResponse *response;
        NSData *responseData =[NSURLConnection sendSynchronousRequest:mutableurlrequest returningResponse:&response error:&err];
        NSString *resStr =[[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];

  //This is for Response
        NSLog(@"got response==%@", resStr);  } 

你想将UIImageView转换为NSData还是将UIImage转换为NSData? - Shanti K
我是新手,所以我在上面声明了代码。只需查看代码即可。 - user3182143
6个回答

7
我认为 Ashu 的回答会返回 null。请尝试以下方法:
NSData *dataImage = [[NSData alloc] init];
dataImage = UIImagePNGRepresentation(image);
NSString *stringImage = [dataImage base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

通过你的代码,我在控制台部分得到了响应,例如:VBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAHGlET1QAAAACAAAA AAAAACAAAAAoAAAAIAAAACAAAAMlNrevzAAAAvFJREFUeAHsmTFPVEEUhQGDMUY7 ErQ3obawotnYUmBLwi+wsbTmH1BCgVkTC3p+ASWEn2BMSLCS0tho1PPhkmzu3vve vLd3Z1fCSQ68vTNz7zmzvHkzj6Wle9zPQO0ZWFHBdfGluDUi18Rou1N4IDcDcV88 F6/En+KfgLTRh76MGYjk+K/wWGrfiEPxWozMlsbJQS5yknth8VDK3onfxFJzXfuR mxrUWhgsS8mO+EXsaqhvf2pRk9pzxaaqX4h9jUw7jtpomAveqmrTgjZu7of6nojv xV3xtbghPh2Ra2K00Ye+jBnPEV2jAS3VsKpKB2Ik6DbO4vVB3Bb7LF6MYeyRSK7b是否正确? - user3182143
收到响应=={"success":1,"message":"问题成功插入!"}但数据详情为=email_id=ravi@gmail.com&cat=Celebrities&q_text=我们怎么做?&q_image1=(null)&q_image2=(null)&q_status=1&last_upd_by=ravi&last_upd_timestamp=2014-01-23 13:25:47,所以图片再次为空。请查看图片,它变成了空值。 - user3182143
警告:'stingImage','stringImage2'的本地声明隐藏了实例变量。 - user3182143
这是编码的代码 //对于image1 imageData = [[NSData alloc] init]; imageData = UIImagePNGRepresentation(imgFirstImg.image); NSString *stringImage = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];NSLog(@"the stringImage is==%@",stringImage); //对于image2 imageData2 = [[NSData alloc] init]; imageData2 = UIImagePNGRepresentation(imgSecondImg.image); NSString *stringImage2 = [imageData2 base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]; 我在viewDidLoad中声明了它们。 - user3182143
还有,您能告诉我如何在iOS中从服务器检索图像吗? - user3182143
显示剩余4条评论

2

很久以前我在这里发表了我的答案。

选项1:将图片上传到服务器和从服务器获取图片

当我们发送图片到服务器(UIImage-NSData-NSString),我们需要使用以下代码:

NSData *postData = UIImageJPEGRepresentation(myImage, 1.0);
NSString *strEncoded  = [postData base64EncodedStringWithOptions:0];

从服务器获取图片时(NSString-NSData-UIImage),我们需要使用以下代码。
NSData *getData  = [[NSData alloc] initWithBase64EncodedString:strEncodedFromServer options:0];
UIImage *image = [UIImage imageWithData:getData];

选项2:简单的字符串编码、解码转换
NSString *strName = @"iOS";
NSData *dataEncoded = [strName dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64EncodedString = [dataEncoded base64EncodedStringWithOptions:0];
NSLog(@"The Encoded String is - %@", base64EncodedString);

NSData *dataDecoded = [[NSData alloc] initWithBase64EncodedString:base64EncodedString options:0];
NSString *strDecoded = [[NSString alloc] initWithData:dataDecoded encoding:NSUTF8StringEncoding];
NSLog(@"The DeCoded String is - %@", strDecoded);

输出屏幕截图如下

enter image description here

选项3:当我们需要对字典进行编码和解码时

NSDictionary *dictEncoded = @{
                                    @"OS":@"iOS",
                                    @"Mobile":@"iPhone",
                                    @"Version":@"iOS10"
                                };

NSData *dataDictEncode = [NSJSONSerialization dataWithJSONObject:dictEncoded options:(NSJSONWritingOptions) 0 error:nil];
NSString *strBase64Encode = [dataDictEncode base64EncodedStringWithOptions:0];
NSLog(@"The encoded dictionary is - %@", strBase64Encode);

NSData *dataDictDecode = [[NSData alloc] initWithBase64EncodedString:strBase64Encode options:0];
NSDictionary *dictDecoded = [NSJSONSerialization JSONObjectWithData:dataDictDecode options:NSJSONReadingMutableContainers error:nil];
NSLog(@"The decoded dictionary is - %@", dictDecoded);

输出结果为:

输入图像描述


我在这里问了一个类似的问题(https://stackoverflow.com/questions/48940176/status-code-400-when-converting-postman-request-into-objective-c)。我也遇到了将Postman请求转换为Objective-C代码的问题。你介意看一下我的问题吗? - fi12

2
// From image to data
NSData *imgData = [NSData dataWithData:UIImagePNGRepresentation(yourImage)];
// From data to string
NSString *string = [[NSString alloc] initWithData:imgData encoding:NSUTF8StringEncoding];

这两个应该在哪里声明?在viewDidLoad还是post方法中? - user3182143
你可以在获取图像后立即声明它,我建议在post方法中这样做。 - Ashutosh
它向我显示警告,例如不兼容的指针类型传递'UIImageView *'到参数类型'UIImage *'。 - user3182143
我认为你在传递imageView时使用了"yourImage",而不是传递ImageView,请传递imageView.image。 - Ashutosh
如果答案有帮助,请不要忘记将其标记为已解决,这将有助于其他社区用户:) - Ashutosh
是的,我现在正在检查代码。一旦它能够正常工作,我会给予评分。我不会忘记这件事的。 - user3182143

1

答案是正确的,将NSString转换为Data再转换为iOS中的UIImage的代码如下:

UIImage *image = nil;

NSString* path =[NSString stringWithFormat: @"%@",@"http://wx.qlogo.cn/mmopen/q9UTH59ty0K1PRvIQkyydYMia4xN3gib2m2FGh0tiaMZrPS9t4yPJFKedOt5gDFUvM6GusdNGWOJVEqGcSsZjdQGKYm9gr60hibd/0"];

NSURL* url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];//网络图片url


NSData* data = [NSData dataWithContentsOfURL:url];//获取网咯图片数据


if(data!=nil)
{
    image = [[UIImage alloc] initWithData:data];//根据图片数据流构造image
}

NSData *dataImage = [[NSData alloc] init];
dataImage = UIImagePNGRepresentation(image);

NSString *stringImage = [dataImage base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

imgstr = stringImage;



NSData *data = [[NSData alloc] initWithBase64EncodedString:imgstr options:NSDataBase64DecodingIgnoreUnknownCharacters];

UIImageView *img1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 300, 200, 200)];

img1.image =[[UIImage alloc] initWithData:data];//根据图片数据流构造image
[self.view addSubview:img1];

0

0

关于使用 Swift 3 进行 Base64 编码

func createImageString(image: UIImage) -> String? {
     if let dataImage = UIImagePNGRepresentation(image) {
         return dataImage.base64EncodedString(options: .lineLength64Characters)
     }
     return nil
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接