簡體   English   中英

將UIImage轉換為NSData,將NSData轉換為NSString,以便將圖像發布到服務器

[英]Converting UIImage to NSData and NSData to NSString for posting images to a server

我有兩個UIImageViews。 我想通過腳本將兩個圖像發布到服務器。 在此之前,我必須將這些圖像轉換為數據和數據到字符串,但我不知道如何將圖像從UIImageView轉換為NSDataNSDataNSString 。我已經引用了所有代碼,但它不起作用。 我還想知道在我的代碼中應該在哪里聲明轉換編碼(圖像到數據和數據到圖像)?

這是我實施的

.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部分

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

我認為Ashu的回答將返回null。 嘗試這個

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

很久以后,我在這里發布我的答案。

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

輸出截圖是

在此輸入圖像描述

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

輸出結果是

在此輸入圖像描述

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

答案是對的,在ios中將NSString轉換為數據到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];

您可以使用以下庫來獲取前7: https//github.com/l4u/NSData-Base64/blob/master/NSData%2BBase64.h (或)如果您的應用程序適用於ios 7及更高版本,那么apple已經添加了類別NSData + Base64,它是內置在ios 7 SDK中的

對於使用swift 3的Base64編碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM