当前位置:  开发笔记 > 编程语言 > 正文

在NSString中解码Base-64编码的PNG

如何解决《在NSString中解码Base-64编码的PNG》经验,为你挑选了3个好方法。

我有一些NSDataBase-64编码,我想解码它,我看到一个看起来像这样的例子

NSData* myPNGData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];

[Base64 initialize];
NSData *data = [Base64 decode:img];
cell.image.image = [UIImage imageWithData:myPNGData];

然而,这给了我一大堆错误,我想知道该怎么做才能使这个工作.我需要将某些类型的文件导入到我的项目中,还是必须包含一个框架?

这些是我得到的错误

Use of undeclared identifier 'Base64'
Use of undeclared identifier 'Base64'
Use of undeclared identifier 'cell'

我到处寻找,无法弄清楚做什么是正确的.



1> bobnoble..:

您可以将Base64编码的字符串解码为NSData:

-(NSData *)dataFromBase64EncodedString:(NSString *)string{
    if (string.length > 0) {

        //the iPhone has base 64 decoding built in but not obviously. The trick is to
        //create a data url that's base 64 encoded and ask an NSData to load it.
        NSString *data64URLString = [NSString stringWithFormat:@"data:;base64,%@", string];
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]];
        return data;
    }
    return nil;
}

使用上述方法从Base64字符串中获取图像的示例:

-(void)imageFromBase64EncodedString{

    NSString *string = @"";  // replace with encocded string
    NSData *imageData = [self dataFromBase64EncodedString:string];
    UIImage *myImage = [UIImage imageWithData:imageData];

    // do something with image
}



2> 小智..:

NSData Base64库文件将为您提供帮助.

#import "NSData+Base64.h"

//Data from your string is decoded & converted to UIImage
UIImage *image = [UIImage imageWithData:[NSData
dataFromBase64String:strData]];

希望能帮助到你

Swift 3版

它几乎是一样的

//Create your NSData object
let data = NSData(base64Encoded: "yourStringData", options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)

//And then just create a new image based on the data object
let image = UIImage(data: data as! Data)

Swift 2.3版本

//Create your NSData object
let data = NSData(base64EncodedString: "yourStringData", options: .IgnoreUnknownCharacters)

//And then just create a new image based on the data object
let image = UIImage(data: data!)


iOS7为此提供了新方法 - (id)initWithBase64EncodedString:(NSString*)base64String选项:(NSDataBase64DecodingOptions)选项和 - (NSString*)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)选项

3> Pierre-Yves ..:
//retrieve your string 

NSString *string64 = //... some string base 64 encoded

//convert your string to data

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

//initiate image from data

UIImage *captcha_image = [[UIImage alloc] initWithData:data];

推荐阅读
爱唱歌的郭少文_
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有