How to display a base64 image within a UIImageView?

后端 未结 11 2071
攒了一身酷
攒了一身酷 2020-11-30 00:56

I got this Base64 gif image:

R0lGODlhDAAMALMBAP8AAP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAACH5BAUKAAEALAAAAAAMAAwAQAQZMMhJK7iY4p3nlZ8XgmN         


        
相关标签:
11条回答
  • 2020-11-30 01:47

    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.

    0 讨论(0)
  • 2020-11-30 01:51

    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.

    0 讨论(0)
  • 2020-11-30 01:51
    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.
    0 讨论(0)
  • 2020-11-30 01:52

    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!)
    
    0 讨论(0)
  • 2020-11-30 01:52

    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)
    
    0 讨论(0)
提交回复
热议问题