将Base64 NSString转换为UIImage?

时间:2015-05-06 15:09:22

标签: ios swift uiwebview uiimage

从UIWebView获取的NSString使用了以下javascript方法:

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

我在视图控制器中获取数据,数据如下所示:

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

那么如何将这些字符串转换为UIImage?谢谢。

1 个答案:

答案 0 :(得分:2)

将base64编码的图像数据放在NSString中,删除该字符串的第一部分并使用NSData对其进行解码:

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

(适用于IOS 7.0及更高版本)