美文网首页
iOS Base64编码(文字/图片)

iOS Base64编码(文字/图片)

作者: wang521921 | 来源:发表于2018-10-30 18:19 被阅读0次

    方法

    • (NSString *)base64EncodedString {
      NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
      return [data base64EncodedStringWithOptions:0];
      }

    • (NSString *)base64DecodedString {
      NSData *data = [[NSData alloc]initWithBase64EncodedString:self options:0];
      return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
      }

    对字符进行Base64编解码

    NSString *sourceStr = @"www.baidu.com";
    NSLog(@"sourceStr---->%@",sourceStr);

    NSString *base64Str = [sourceStr base64EncodedString];
    NSLog(@"Base64编码---->%@",base64Str);

    NSString *decodeStr = [base64Str base64DecodedString];
    NSLog(@"Base64解码---->%@",decodeStr);

    /*
    sourceStr---->www.baidu.com
    Base64编码---->d3d3LmJhaWR1LmNvbQ==
    Base64解码---->www.baidu.com
    */

    对图片进行Base64编解码

    // UIImage图片转成Base64字符串:
    UIImage *img = [UIImage imageNamed:@"0.jpg"];
    NSData *imgData = UIImageJPEGRepresentation(img, 1.0f);
    NSString *encodedImgStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];

    NSLog(@"encodedImgStr---->%@",encodedImgStr);

    //Base64字符串转UIImage图片:
    NSData *decodedImgData = [[NSData alloc] initWithBase64EncodedString:encodedImgStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    UIImage *decodedImage = [UIImage imageWithData:decodedImgData];
    UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.width)];
    imgV.contentMode = UIViewContentModeScaleAspectFit;
    [imgV setImage:decodedImage];
    [self.view addSubview:imgV];

    NSLog(@"decodedImage---->%@",decodedImgData);

    782332-20170424020339303-208432037.png

    相关文章

      网友评论

          本文标题:iOS Base64编码(文字/图片)

          本文链接:https://www.haomeiwen.com/subject/nqqntqtx.html