Converting UIImage to NSData and NSData to NSString for posting images to a server

13,972

Solution 1

After Long time I post my answer here.

Option 1 : Image to server and Image from Server

When we send image to server(UIImage-NSData-NSString), we need to use below coding

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

When we get the image from server(NSString-NSData-UIImage),we need to use below coding

NSData *getData  = [[NSData alloc] initWithBase64EncodedString:strEncodedFromServer options:0];
UIImage *image = [UIImage imageWithData:getData];

Option 2 : Simple String Encode,Decode Conversion

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

Output Screenshot is

enter image description here

Option 3 : When we need to encode and decode the dictionary

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

Output result is

enter image description here

Solution 2

I think Ashu's answer will return a null. try this

NSData *dataImage = [[NSData alloc] init];
dataImage = UIImagePNGRepresentation(image);
NSString *stringImage = [dataImage base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

Solution 3

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

Solution 4

the answer is right ,and converting NSString to Data to Uiimage in ios is below:

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];
Share:
13,972
user3182143
Author by

user3182143

Updated on June 05, 2022

Comments

  • user3182143
    user3182143 almost 2 years

    I have two UIImageViews. I want to post two images to server through the script. Before that I have to convert these images to data and data to string but I don't know how to convert the images from UIImageView to NSData and NSData to NSString.I have referred all the codes but it does not work. I would also like to know as to where should I declare the conversion coding (image to data and data to image) in my code?

    This is what I have implemented

    .h part

      #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);  } 
    
  • user3182143
    user3182143 over 10 years
    where should i declare these two? in viewDidLoad or post method?
  • Ashutosh
    Ashutosh over 10 years
    you can declare this just after getting image, I suggest to do it in post method..
  • user3182143
    user3182143 over 10 years
    It shows me warning like Incompatible pointer types passing 'UIImageView *' to parameter type 'UIImage *'
  • Ashutosh
    Ashutosh over 10 years
    I think you are passing imageView in place of "yourImage", instead of passing ImageView, pass imageView.image.
  • Ashutosh
    Ashutosh over 10 years
    If answear helps then please dont forget to check mark it as it will help other community users too:)
  • user3182143
    user3182143 over 10 years
    yeah i am checking the code now.Once it works i give the mark.I never forget to do that.
  • user3182143
    user3182143 over 10 years
    through your code i am getting response in console part like VBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAHGlET1QAAAACA‌​AAA AAAAACAAAAAoAAAAIAAAACAAAAMlNrevzAAAAvFJREFUeAHsmTFPVEEUhQGD‌​MUY7 ErQ3obawotnYUmBLwi+wsbTmH1BCgVkTC3p+ASWEn2BMSLCS0tho1PPhkmzu‌​3vve vLd3Z1fCSQ68vTNz7zmzvHkzj6Wle9zPQO0ZWFHBdfGluDUi18Rou1N4IDcD‌​cV88 F6/En+KfgLTRh76MGYjk+K/wWGrfiEPxWozMlsbJQS5yknth8VDK3onfxFJz‌​XfuR mxrUWhgsS8mO+EXsaqhvf2pRk9pzxaaqX4h9jUw7jtpomAveqmrTgjZu7of6‌​nojv xV3xtbghPh2Ra2K00Ye+jBnPEV2jAS3VsKpKB2Ik6DbO4vVB3Bb7LF6MYeyR‌​SK7b is it correct?
  • Aravind G S
    Aravind G S over 10 years
    yeah... in the server side store it like this and when you retrieve you can decode it back to nsdata and back to uiimage
  • user3182143
    user3182143 over 10 years
    k i il try and tell you after the posting image.
  • user3182143
    user3182143 over 10 years
    got response=={"success":1,"message":"Questions successfully inserted!"} but the the data Details is [email protected]&cat=Celebrities&q_text= How can we done?&q_image1=(null)&q_image2=(null)&q_status=1&last_upd_by‌​=ravi&last_upd_times‌​tamp=2014-01-23 13:25:47 so again the image is null.Please see the image it got null.
  • user3182143
    user3182143 over 10 years
    Warning is local declaration of 'stingImage','stringImage2', hides the instance variable.
  • user3182143
    user3182143 over 10 years
    Actually i declared these in viewDidLoad method.
  • user3182143
    user3182143 over 10 years
    these are the coding //For image1 imageData =[[NSData alloc]init]; imageData =UIImagePNGRepresentation(imgFirstImg.image); NSString *stringImage = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64Charact‌​erLineLength]; NSLog(@"the stringImage is==%@",stringImage); //for image2 imageData2 =[[NSData alloc]init]; imageData2 =UIImagePNGRepresentation(imgSecondImg.image); NSString *stringImage2 = [imageData2 base64EncodedStringWithOptions:NSDataBase64Encoding64Charact‌​erLineLength]; i declared in viewDidLoad
  • Aravind G S
    Aravind G S over 10 years
    are you using a post request to get the image in your backend?? are you using a php backend, if yes just send me the backend code where you read the image info .. [email protected]
  • user3182143
    user3182143 over 10 years
    also can you tel me how to retrive the image from server in ios?
  • fi12
    fi12 about 6 years
    I asked a similar question here. I'm also having trouble converting a Postman request to Objective-C code. Would you mind taking a look at my question?