如何在UIImageView中显示base64图像?

时间:2009-09-02 10:10:30

标签: objective-c iphone uiimageview uiimage

我得到了这个Base64 gif图片:

R0lGODlhDAAMALMBAP8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAACH5BAUKAAEALAAAAAAMAAwAQAQZMMhJK7iY4p3nlZ8XgmNlnibXdVqolmhcRQA7

现在我想在我的iPhone应用程序中显示这个Base64字符串。

我可以通过使用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];

是否可以使用UIImageView做同样的事情?

11 个答案:

答案 0 :(得分:126)

您不必编码。只需创建一个NSUrl,它就知道“data:” - url。

NSURL *url = [NSURL URLWithString:base64String];    
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *ret = [UIImage imageWithData:imageData];

如评论中所述,您必须确保使用data:image/png;base64,添加数据,否则您的base64数据将无用。

答案 1 :(得分:68)

非常古老的问题,但是从iOS7开始,有一种新的,更简单的方法,因此我在这里写它,以便未来的读者可以使用它。

NSData* data = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
UIImage* image = [UIImage imageWithData:data];

非常易于使用,并且不会达到URL的2048字节大小限制。

答案 2 :(得分:15)

此代码将显示base64编码的字符串作为图片:

NSString *str = @"data:image/jpg;base64,";
str = [str stringByAppendingString:restauInfo.picture];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];

restauInfo.picture是一个NSString,它包含base64编码的JPG

就我而言,“restauInfo.picture”中的值来自数据库

答案 3 :(得分:7)

您可以执行以下操作:

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

然后这样称呼:

UIImage *image = [self decodeBase64ToImage:dataString];

答案 4 :(得分:4)

  1. 将Base64解码为原始二进制文件。你在这里独自一人。您可能会发现cStringUsingEncoding: NSString有用。
  2. 使用NSData
  3. 创建dataWithBytes:length:实例
  4. 使用[UIImage imageWithData:]加载它。

答案 5 :(得分:2)

感谢porneL

我可以使用谷歌找到一个Base64脚本: Base64.m

所以我稍微修改了一下,可以得到一个有效的测试代码:

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

答案 6 :(得分:1)

以防万一有人正在寻找 Swift 代码来实现这一目标(基于Jonathan M提供的 Objective-C 答案),这里是:

var data = NSData (base64EncodedString: base64String, options: NSDataBase64DecodingOptions(0))
var image = UIImage(data: data!)

答案 7 :(得分:1)

目标C

NSString *plainString = @"foo";

编码

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String);  

解码

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); 

NSURL *URL = [NSURL URLWithString:
  [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
       base64String]];

 return [NSData dataWithContentsOfURL:URL];

夫特

let plainString = "foo"

编码

let plainData = (plainString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0)!)
println(base64String) 

解码

let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions.fromRaw(0)!)
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)    
println(decodedString) // foo

答案 8 :(得分:1)

在我的案例中,由@Masche提出了一个解决方案。正如我在 Swift 2.0 中所需要的那样:

let url = NSURL(string: imageString)
let data = NSData.init(contentsOfURL: url!)
let image = UIImage(data: imageData)

答案 9 :(得分:0)

用于下载内部带有base64图像字符串的文本文件的代码片段,然后保存/读取文件,最后创建要在视图中显示的图像

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

答案 10 :(得分:0)

快速4 +

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