圖片轉換成字符串上傳到服務器及字符串轉換為圖片


#pragma mark  -------  UIImage圖片轉成base64字符串:

//將 已轉換成為 NSData 類型的圖片 轉換為 NSString 類型

//iOS 7.0+      ----    base64EncodedStringWithOptions

    NSString *_encodedImageStr = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    NSLog(@"===Encoded image:\n%@", _encodedImageStr);

  NSString *urlStr = [NSString stringWithFormat:kURLStr];

    NSDictionary *params = @{

                             @"username":[NSString stringWithFormat:@"%@", [Singleton mainSingleton].telephoneData],

                             @"image":_encodedImageStr

                             };

  AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager POST:urlStr parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

   //獲取存在本地沙盒的圖片,前提是同一界面內做過 “將圖片存在本地沙盒中” 的這一操作。

         [formData appendPartWithFileURL:[NSURL fileURLWithPath:fullPath] name:@"file" fileName:@"currentImage.png" mimeType:@"image/png" error:nil];

    } progress:^(NSProgress * _Nonnull uploadProgress) {

         // @property int64_t totalUnitCount;     需要下載文件的總大小

        // @property int64_t completedUnitCount; 當前已經下載的大小

        //打印下上傳進度

        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        //請求成功

        NSLog(@"請求成功:%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        //請求失敗

        NSLog(@"請求失敗:%@",error);

    }];

 

#pragma mark  -------  Base64字符串轉UIImage圖片:

//從網絡端解析下來的字符串轉換為圖片顯示

  NSData *_decodedImageData   = [[NSData alloc] initWithBase64EncodedString:[responseObject[@"items"] objectForKey:@"faceimageurl"]

  options:NSDataBase64DecodingIgnoreUnknownCharacters];//NSDataBase64Encoding64CharacterLineLength

      UIImage *_decodedImage      = [UIImage imageWithData:_decodedImageData];

//   NSLog(@"===Decoded image size: %@", NSStringFromCGSize(_decodedImage.size));

      self.avatarImageV.image = _decodedImage;

 

PS:以上全部適用於 iOS7.0+

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM