Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Base-64 encoded PNG in an NSString

I have some NSData which is Base-64 encoded and I would like to decode it, I have seen an example that looks like this

NSData* myPNGData = [xmlString dataUsingEncoding:NSUTF8StringEncoding];

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

However this gives me a load of errors, I would like to know what to do in order to get this to work. Is there some type of file I need to import into my project or do I have to include a framework?

These are the errors I get

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

I have looked everywhere and cannot figure out what is the proper thing to do.

like image 989
HurkNburkS Avatar asked May 23 '13 02:05

HurkNburkS


People also ask

How do I decode a base64 encoded file?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.

How do I decode Base 64 in node JS?

The Base64 decoding process is very much similar to the encoding process. All you need to do is create a buffer from the Base64 encoding string by using base64 as the second parameter to Buffer. from() and then decode it to the UTF-8 string by using the toString() method.

What is base64 data image png?

data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).


1 Answers

You can decode a Base64 encoded string to 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;
}

Example use of above method to get an image from the Base64 string:

-(void)imageFromBase64EncodedString{

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

    // do something with image
}
like image 103
bobnoble Avatar answered Oct 10 '22 12:10

bobnoble