bmjohns
bmjohns

Reputation: 6470

Converting a Base64 String into a UIImage

I have looked at similar answers to this type of question but am still falling short of converting a Base64 encoded string into a UIImage correctly. I have used http://www.freeformatter.com/base64-encoder.html to test my string and can successfully get an image back as a response.

However, when I use initWithBase64EncodedString, I get a nil response. Below is the code I am using and an example of the Base64 string that I used to test with. What am I missing here?

Code:

imageData = [[NSData alloc] initWithBase64EncodedString:checkBytesString options:0]; checkImage = [UIImage imageWithData:imageData];

String (It is rather large so I am sharing it via OneDrive):

https://onedrive.live.com/redir?resid=60AA391B8FEA9C36!107&authkey=!AFK_y5UHOFsdYsKZI&ithint=file%2c.rtf

Upvotes: 0

Views: 1977

Answers (2)

bmjohns
bmjohns

Reputation: 6470

Answer was to use an external library, NSData+Base64. It implements method dataFromBase64String that returned imageData properly so it could be converted into an image.

https://github.com/l4u/NSData-Base64

imageData = [NSData dataFromBase64String:frontCheckBytesString];
checkImage = [UIImage imageWithData:imageData];

Upvotes: 2

Vaibhav Saran
Vaibhav Saran

Reputation: 12908

Simple in iOS 7 onwards

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}

UIImage *zeroImage = [[UIImage alloc]init];
if(![strb64Image isEqualToString:@""] && strb64Image)
{
    zeroImage = [self decodeBase64ToImage:strB64Image];
}

Upvotes: 1

Related Questions