Honey
Honey

Reputation: 2880

Converting byte array to image in xcode?

I am getting a byte array(I reckon) in NSMutableArray's object.The NSMutableArray i get is from Xml parsing from a service URL..Now I need to convert that byte array to UIImage ..Gone through google and found to convert to NSData and then UIImage but couldn't understand how..? How can I do it ?

My array looks like this :

(
{
        Name = "John";
        Image = "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJS
kcgSlBFRyB2NjIpLCBxdWFsaXR5ID0gODAK/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXF
BYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgEKwZAAwEiAAIRAQMRAf/........
 //big byte array 
}
)

First of all I need to clear whether it is a byte array ?How can I extract image from this ?

Upvotes: 1

Views: 3580

Answers (1)

Codo
Codo

Reputation: 79023

Your data is organized like this:

  • The out-most data structure is a NSArray or NSMutableArray (as you write).
  • At index 0 (first element in array), there's an NSDictionary instance.
  • In the dictionary, there are two key-value pairs. One has the key Image and a string as the value.
  • The string value is binary data, encoded as Base64.
  • The binary data is the image data.

So the get the image, you need to go this path:

NSMutableArray* array = ... // from XML
NSDictionary* dict = [array objectAtIndex: 0];
NSString* dataString = [dict objectForKey: @"Image"];
NSData* imageData = [dataString base64DecodedData];
UIImage* image = [UIImage imageWithData: imageData];

Note that the Base64 decoding is not part of iOS. But there are many implementations on the net for decoding a string into data. Just google it.

A Base64 implementation that looks good and simple can be found on GitHub.

Upvotes: 5

Related Questions