leizh00701 leizh00701 - 12 days ago 6
Swift Question

Convert a Base64 NSString to UIImage?

The NSString is got from UIWebView used the following javascript method:

function() {
var img=document.getElementById("myimg");
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
context.drawImage(img,0,0,img.width,img.height);
return canvas.toDataURL("image/png");



I get the data in view controller , the data is look like this:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWcAAAENCAYAAADT16SxAAAAAXNSR0IArs4c6QAAQABJREFUeAHsvVmQZNd55/dl3ty3ytq7qpfqBrrRxMINBAmSosRVImnNaGSLmhnZMQo/eCZinvzkB4cdDj84YuyYGEeM7YeZUHjGDI9CoRlaskc7KXETuIEAsS+NBhq9d+1bVu6bf/9z61ZnV1ejq8FGsxN1LlCdmTfvPfec75zz//7nf75zMmZmff784S3gLfBzWiCIxa3f79Ohwi4Vtxj/3Xh09tndYrHdd96Yjj7pWfs59kpr970x8m67ctvvd/eTvF3PqvKsdJS3/d3rLvb/7GmB0JJ7fuVPegt4C9yJBQaB+U7u89d6C+xlgcReJ/05bwFvgTu3QMSYozt7+2TJ0fX+1Vtg0AIen......


So how can I convert those string to UIImage ? Thank you.

Answer

Place the base64 encoded image data in a NSString removing the first part of that string and decode it using NSData:

NSString *base64Str = [myString substringFromIndex:22];
NSData *data = [[NSData alloc]initWithBase64EncodedString:base64Str 
                                                  options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage* myImg=[UIImage imageWithData:data];

(Works with IOS 7.0 and later)

Comments