How to display a base64 image within a UIImageView?

Objective CIphoneUiimageviewUiimage

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

You don't have to encode it. Simply make a NSUrl, it knows the "data:"-url.

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 that you prepend your data with data:image/png;base64, or else your base64 data is useless.

Solution 2 - Objective C

Very old question, but as of iOS7 there is a new, much easier way to do so, hence I'm writing it here so future readers can 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.

Solution 3 - Objective C

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

Solution 4 - Objective C

You can do something 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];
             

Solution 5 - Objective C

  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.

Solution 6 - Objective C

Thanks porneL

I could find a Base64 script using google: Base64.m

So I modified it a little bit and could get 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 can access my image data:
aUIImageView.image = [UIImage imageWithData: [NSData dataWithData:mutableData]];

Solution 7 - Objective C

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

Solution 8 - Objective C

Swift 4+

let base64EncodedString = "" // Your Base64 Encoded String
if let imageData = Data(base64Encoded: base64EncodedString) {
                let image = UIImage(data: imageData)
                self.imageView.image = image
            }

Solution 9 - Objective C

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!)

Solution 10 - Objective C

In my case worked a solution 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)

Solution 11 - Objective C

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;
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjantimonView Question on Stackoverflow
Solution 1 - Objective CmascheView Answer on Stackoverflow
Solution 2 - Objective CJonathan MView Answer on Stackoverflow
Solution 3 - Objective CThorsten NiehuesView Answer on Stackoverflow
Solution 4 - Objective CRadford7821View Answer on Stackoverflow
Solution 5 - Objective CKornelView Answer on Stackoverflow
Solution 6 - Objective CjantimonView Answer on Stackoverflow
Solution 7 - Objective CCarlos ParadaView Answer on Stackoverflow
Solution 8 - Objective CMaverickView Answer on Stackoverflow
Solution 9 - Objective CMartinView Answer on Stackoverflow
Solution 10 - Objective CJulianView Answer on Stackoverflow
Solution 11 - Objective Cd1jhoni1bView Answer on Stackoverflow