How to display a base64 image within a UIImageView?


How to display a base64 image within a UIImageView?



I got this Base64 gif image:

R0lGODlhDAAMALMBAP8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAACH5BAUKAAEALAAAAAAMAAwAQAQZMMhJK7iY4p3nlZ8XgmNlnibXdVqolmhcRQA7 

Now I want to display this Base64 String within my IPhone App.

I could get this working by using the WebView:

aUIWebView.scalesPageToFit = NO; aUIWebView.opaque = NO; aUIWebView.backgroundColor = [UIColor clearColor];  [aUIWebView loadHTMLString:   @"<html><body style=""background-color: transparent""><img src=""data:image/png;base64,R0lGODlhDAAMALMBAP8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAUKAAEALAAAAAAMAAwAQAQZMMhJK7iY4p3nlZ8XgmNlnibXdVqolmhcRQA7"" /></body></html>"  baseURL:nil]; 

Is it possible to do the same thing by using the UIImageView?


Having trouble adding objects to NSMutableArray in Objective C

1:

How can I rotate an UIImageView by 20 degrees?
You don't have to encode it. Replacing a document body on the iPhoneSimply make a NSUrl, it knows the "data:"-url. iPhone App: How to get data from an API, parse, and store for later use?. xcode gives syntax error on cpp code
NSURL *url = [NSURL URLWithString:base64String];     NSData *imageData = [NSData dataWithContentsOfURL:url]; UIImage *ret = [UIImage imageWithData:imageData]; 
As mentioned in the comments, you have to make sure this you prepend your data with data:image/png;base64, or else your base64 data is useless.. Generate Xml
How to resolve 'unrecognized selector sent to instance'?How do I enable directional lock for a UIScrollView?

2:

Very old question, although as of iOS7 there is a new, enough easier way to did so, hence I'm writing it here so future readers must use this..
NSData* data = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; UIImage* image = [UIImage imageWithData:data]; 
Very easy to use, and will not hit the 2048 byte size limit of a URL..

3:

This Code will display an base64 encoded string as a picture:.
NSString *str = @"data:image/jpg;base64,"; str = [str stringByAppendingString:restauInfo.picture]; NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]]; 
restauInfo.picture is an NSString which contains the base64 encoded JPG. In my case the Value from "restauInfo.picture" comes from a database.

4:

You must did any thing like the following:.
(UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {   NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];   return [UIImage imageWithData:data]; } 
Then call it like this:.
UIImage *image = [self decodeBase64ToImage:dataString]; 

5:

  1. Decode Base64 to raw binary. You're on your own here. You might find cStringUsingEncoding: of NSString useful.
  2. Create NSData instance using dataWithBytes:length:
  3. Use [UIImage imageWithData:] to load it.

6:

Thanks porneL. I could find a Base64 script using google: Base64.m. So I modified it a little bit and could receive a working test code:.
NSString * base64img = @"R0lGODlhDAAMALMBAP8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAUKAAEALAAAAAAMAAwAQAQZMMhJK7iY4p3nlZ8XgmNlnibXdVqolmhcRQA7"; base64Data = [base64img dataUsingEncoding:NSASCIIStringEncoding]; base64Bytes = [base64Data bytes]; mutableData = [NSMutableData dataWithCapacity:[base64Data length]]; lentext = [base64Data length];  while( YES ) {        if( ixtext >= lentext ) break;        ch = base64Bytes[ixtext++];        flignore = NO;         if( ( ch >= 'A' ) && ( ch <= 'Z' ) ) ch = ch - 'A';        else if( ( ch >= 'a' ) && ( ch <= 'z' ) ) ch = ch - 'a' + 26;        else if( ( ch >= '0' ) && ( ch <= '9' ) ) ch = ch - '0' + 52;     else if( ch == '+' ) ch = 62;        else if( ch == '=' ) flendtext = YES;        else if( ch == '/' ) ch = 63;        else flignore = YES;         if( ! flignore ) {     	short ctcharsinbuf = 3;     	BOOL flbreak = NO;      	if( flendtext ) {     		if( ! ixinbuf ) break;     		if( ( ixinbuf == 1 ) || ( ixinbuf == 2 ) ) ctcharsinbuf = 1;     		else ctcharsinbuf = 2;     		ixinbuf = 3;     		flbreak = YES;     	}      	inbuf [ixinbuf++] = ch;      	if( ixinbuf == 4 ) {     		ixinbuf = 0;     		outbuf [0] = ( inbuf[0] << 2 ) | ( ( inbuf[1] & 0x30) >> 4 );     		outbuf [1] = ( ( inbuf[1] & 0x0F ) << 4 ) | ( ( inbuf[2] & 0x3C ) >> 2 );     		outbuf [2] = ( ( inbuf[2] & 0x03 ) << 6 ) | ( inbuf[3] & 0x3F );      		for( i = 0; i < ctcharsinbuf; i++ )     			[mutableData appendBytes:&outbuf[i] length:1];     	}      	if( flbreak )  break;        } }   //Finally I must access my image data: aUIImageView.image = [UIImage imageWithData: [NSData dataWithData:mutableData]]; 

7:

Just in case anyone is looking for the Swift code to accomplish this (based on the Objective-C answer provided by Jonathan M), here it is:.
var data = NSData (base64EncodedString: base64String, options: NSDataBase64DecodingOptions(0)) var image = UIImage(data: data!) 

8:

Objective-C

NSString *plainString = @"foo"; 
Encoding .
NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding]; NSString *base64String = [plainData base64EncodedStringWithOptions:0]; NSLog(@"%@", base64String);   
Decoding.
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding]; NSLog(@"%@", decodedString);  
Option.
NSURL *URL = [NSURL URLWithString:   [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",        base64String]];   return [NSData dataWithContentsOfURL:URL]; 

Swift

let plainString = "foo" 
Encoding .
let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding) let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!) println(base64String)  
Decoding.
let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!) let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)     println(decodedString) // foo 

9:

In my case worked a quick fix proposed here by @Masche. As I needed it in Swift 2.0 so:.
let url = NSURL(string: imageString) let data = NSData.init(contentsOfURL: url!) let image = UIImage(data: imageData) 

10:

Code snippet for downloading a text file with base64 image string inside, then saving/reading the file and finally creating an image to display right in the view. In Case You Need To Decode Image To Base64 Click Here.
NSString *downloadUrl = "http://www.server.com/file.txt"; // NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: downloadUrl]]; // // DOWNLOAD THE FILE // [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {     if (error) {          NSLog(@"Download Error:%@",error.description);      }     if (data) {         [data writeToFile:filePath atomically:YES];         //         // PROCESS BASE 64 STRING         //         NSString * fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];         //         // PROCESS BASE 64 STRING         //         NSString *base64String = fileContents;         NSURL *url = [NSURL URLWithString:base64String];         NSData *imageData = [NSData dataWithContentsOfURL:url];         //         // CREATE IMAGE         //         UIImage *ret = [UIImage imageWithData:imageData];         self.myImage.image = ret;     } } 


64 out of 100 based on 39 user ratings 874 reviews