Objective-c Base64 NSString to NSData conversion - ios

I am trying to load in a very large string that is a base64 encoded PNG into NSData to create a UIImage on the fly. I can get the image generated by it is very distorted. Am I doing this correctly? I am also using SBJson in this example.
// Data is the NSData loaded in from the web
NSString *responseValue = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *successData = [(NSDictionary*)[responseValue JSONValue] objectForKey:#"MapFlightResult"];
NSData *pngData = [[NSData alloc] initWithBase64EncodedString:successData options:1];
UIImage *map = [UIImage imageWithData:mapData];
[imageView setImage:map];

I believe you issue is that your not sending in a base64 encoded string to initWithBase64EncodedString.

Related

Base 64 image into uiimage - Objective-C

I'm trying to insert a base 64 image into UIImage in Objective-C I do the following:
I have the user's image into a NSURL
NSURL *url = [NSURL URLWithString: [fetchDefaults objectForKey:#"img"]];
Then I cast the url, into a NSString
NSString *string=[NSString stringWithFormat:#"%#",url];
Then I clean the string, and add the prefix "data:application/octet-stream;base64," also tried with "data:image/jpg;base64,"
NSMutableString *tempStr = [NSMutableString stringWithString:string];
[tempStr replaceOccurrencesOfString:#" " withString:#"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
NSString *temp = [[NSString stringWithFormat:#"data:application/octet-stream;base64,%#",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
And finally the string is cast to an NSData to be inserted into UImage
NSData *dat = [[NSData alloc]initWithBase64EncodedString:temp options:NSDataBase64DecodingIgnoreUnknownCharacters];
[avatar setImage:[UIImage imageWithData:dat]];
Despite of value of dat is not nil, when I set the image to the UIImage the image isn't showed, any idea of what am I doing wrong?
From what I understand you have your base64 string in fetchDefaults.
/*Get base64 string*/
NSString *base64 = [fetchDefaults objectForKey:#"img"];
Use this NSData category: https://searchcode.com/codesearch/view/40028750/
/*Convert base64 to NSData object*/
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64];
/*Convert data to UIImage object*/
UIImage *image = [[UIImage alloc] initWithData:data];

Base64 String when decoded to png is cut off with Objective-C

I'm converting an image that I retrieved from a URL to base 64 using this code.
NSURL* imageUrl = [NSURL URLWithString:url];
NSData* urlData = [NSData dataWithContentsOfURL:imageUrl];
UIImage* uiImage = [UIImage imageWithData: urlData];
NSData* imageData = UIImagePNGRepresentation(uiImage);
NSData* base64 = [imageData base64EncodedDataWithOptions:0];
return [NSString stringWithUTF8String:[base64 bytes]];
the image url: https://api.qrserver.com/v1/create-qr-code/?data=somedata&size=220x220&margin=0
the generated base64 image.
iVBORw0KGgoAAAANSUhEUgAAANwAAADcCAMAAAAshD+zAAAABlBMVEX///8AAABVwtN+AAAAHGlET1QAAAACAAAAAAAAAG4AAAAoAAAAbgAAAG4AAASMOw2BmAAABFhJREFUeAHsmdFq5VYQBO3//+lADqgKUZcjpNU6xLNP5e7puVLPTWI2X99/6s9X/WF5uV/Y3/gSH6L3P1vF04lYKRHEnpdTF5dwLnetJr5tEEk0EfZ8LdXFJZyv5bWa9HU7kOQhGbDna6kuLuFv+Vr6+3KVVSCRFLHVp0RwF2cyyXE4Rzci6f6HJuOENrZ25mSKbP/e1Zh5RG861BQP92v3kbu4NhU6DtfkTiOtllPUJnyJILZ2Yu/IcXiXKp+0HiRFpfElgtjaib0jx+FdqnzSepAUlcaXCGJrJ/aOHId3qfJJ60FSVBpfIoitndg7chzepconrQdJUWl8iSC2dmLvyHF4lyqftB4kRaXxJYLY2om9I8fhXap80nqQFJXGlwhiayf2jhyHSaE15SSiiLzEDZLRy0lMZKfs/C+q/MTehAoRR9sRmXm51QWNuRs4fWxRTiKKCEncIJm53OqCwtwNnD62KCcRRYQkbpDMXG51QWHuBk4fW5STiCJCEjdIZi63uqAwdwOnjy3KSUQRIYkbJDOXW11QmLuB08cW5eRGxM5fitL+L14ua8inlwhmXGJixxlNH1uUkxsRey63qqQRVZuYk1ljxiX2pkPNycO991d72pnIetnzcirjX+yaDlXjh2bAt3ow9vzbcnVxVKOvYv91urpL7E2HqsyhGfCtHow9l1tdHNW8fTk+SKR7JDIqO0X5YE7qRdMnLspJxCTFEwnJTlE+mJPzchS0qGtCLTrvOP9MRk6K8sGcnMtR0KKuCbXovOP8Mxk5KcoHc3IuR0GLuibUovOO889k5KQoH8zJuRwFLeqaUIvOO84/k5GTonwwJ3/f5ahhR1T3+Jfc46Ny5+FuwXF4G4sB0vNyqwtK2nXD5HXyTvh6nknSc7n
I figured out the image is only halved because I checked using this tool.
http://codebeautify.org/base64-to-image-converter
Is there anyway I can generate a base64image String that contains the whole image?
In terms of why it's getting cut off, I suspect you're looking at the base64 string in the debugger, which will truncate it. Actually NSLog the string and you'll see it's longer than what you're seeing in the debugger.
A couple of other unrelated observations:
You should not use stringWithUTF8String with [base64 bytes] because the NSData will not be null terminated. If you really needed to convert it to a string, you'd use initWithData rather than stringWithUTF8String:
return [[NSString alloc] initWithData:base64 encoding:NSUTF8StringEncoding];
As others have pointed out, you can bypass the creation of the NSData of the base64 altogether, and create the string directly:
return [imageData base64EncodedStringWithOptions:0];
I'm not sure why you're taking the NSData from the server and round tripping it through a UIImage at all. You can theoretically just encode the data from the server directly:
NSURL* imageUrl = [NSURL URLWithString:url];
NSData* urlData = [NSData dataWithContentsOfURL:imageUrl];
return [urlData base64EncodedStringWithOptions:0];
The server is already returning you the NSData of a PNG representation. You don't need to do that UIImage and UIImagePNGRepresentation stuff at all. You're actually generating a PNG that is considerably larger than the one the server returned to you.
I'd advise against using dataWithContentsOfURL, because that's a synchronous network call. You probably should use NSURLSession and change this to be an asynchronous method.
NSURL* imageUrl = [NSURL URLWithString:#"https://api.qrserver.com/v1/create-qr-code/?data=somedata&size=220x220&margin=0"];
NSData *data = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:data];
NSString *base64 = [self encodeToBase64String:image];
To convert your image to base64 String use following code:
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
That base64 will give you full image. Tested with your given image
Here is base 64 :
https://gist.github.com/anonymous/6d76e3ad852b4879ab097e6a1b3e68a2
To convert your UIImage into base64 string you can use this code.
NSString *base64String = [UIImagePNGRepresentation(uiImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
Here is the code.
NSURL* imageUrl = [NSURL URLWithString:#"https://api.qrserver.com/v1/create-qr-code/?data=somedata&size=220x220&margin=0"];
NSData* urlData = [NSData dataWithContentsOfURL:imageUrl];
UIImage* uiImage = [UIImage imageWithData: urlData];
NSString *base64String = [UIImagePNGRepresentation(uiImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSLog(#"%#",base64String);
I checked the result string on http://codebeautify.org/base64-to-image-converter
Try it, Hope it helps.
This is working perfectly
UIImage *img = [UIImage imageNamed:#"QRcode.png"];
NSString *base64 = [UIImagePNGRepresentation(img)base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSLog(base64);
The printed base64 String can be converted back to image in the URL you provided

Base 64 decoding produces empty

Im using the following code to convert base64 string to ordinary string.
NSError *localError = nil;
NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:myString options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"encoded string , %#",myString);
NSLog(#"Decode String Value: %#", decodedString);
Encoded string prints the base64 string but the decoded string is empty. Why so?
Avoid converting to a string before decoding:
NSData *decodedData = [[NSData alloc] initWithBase64EncodedData:data options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
Some implementations of Base64 add line breaks every 64 characters. You should be able to address this by using this option: NSDataBase64DecodingIgnoreUnknownCharacters.
If you want to encode and decode data then you can use this code.
// Create NSData object
NSData *data1 =[#"My String" dataUsingEncoding:NSUTF8StringEncoding];
// Encoded NSString from NSData
NSString *base64Encoded = [data1 base64EncodedStringWithOptions:0];
NSLog(#"%#",base64Encoded);
// Encoding data
NSData *base64Data = [data1 base64EncodedDataWithOptions:0];
NSLog(#"%#",base64Data);
// Decoding data
NSData *nsdataDecoded = [base64Data initWithBase64EncodedData:base64Data options:0];
NSString *str = [[NSString alloc] initWithData:nsdataDecoded encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
You can use Base64 library to encode or decode,
https://github.com/dasdom/hAppy/tree/master/base64
Then you can use this code,
NSString *strEncoded = [Base64 encode:data];

How to convert NSData with textEncoding utf-8 into NSURL

I want to convert NSData (textEncoding utf-8) into NSURL.
I am writing below code for this, but conversion from NSData to NSString returning nil. (May be due to encoding type)
NSString *stringFromData = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding]; // stringFromData is nil after execution of this line.
NSURL *url = [[NSURL alloc] initWithString:stringFromData];
So what should I do to convert NSData into NSURL in my case.
But when I am trying to load this data into webview, Its working good. Here is my code to load this data into webview.
[self.webView loadData:myData MIMEType:#"application/pdf" textEncodingName:#"utf-8" baseURL:nil]; //PDF is showing in my webview.
but I am not able to convert this NSData into NSURL. What encoding should I use to convert NSData with textEncoding utf-8 into NSURL ?
You're trying to load data that represents a PDF into an NSString. A PDF file does not consist of UTF-8 encoded characters that represent text, it's a file that contains header information, fonts, vector graphics AND text.
The only solution to your problem in my mind is change the source of the NSData to something that will provide UTF-8 encoded characters that make up a URL.
If you can't get data any other way, why not check if you can extract the textual data from the PDF? https://github.com/zachron/pdfiphone
Have you tried writing the data to local file,
NSString *docPath = [NSHomeDirectory() stringByAppendingString:#"/Documents"];
NSString *pdfFilePath = [docPath stringByAppendingPathComponent:#"pdfFile.pdf"];
BOOL success = [myData writeToFile:pdfFilePath atomically:YES];
if (success) {
NSURL *url = [[NSURL alloc] initFileURLWithPath:pdfFilePath];
NSLog(#"url from data : %#",url);
}
Hope this helps.
Thanks
Ok, try this:
//Convert data to string
NSString *urlString = [[NSString alloc] initWithData:self encoding:NSUTF8StringEncoding];
//Convert the string to URL
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Decode base64 string for image

I have encoded string in base64 and want to decode it but getting nil in NSData *decodedData. NSString *images contains encoded string.
NSString *images = encoded string;
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:images options:0];
UIImage *myImage = [UIImage imageWithData:decodedData];
Perhaps you have unknown characters? Try passing NSDataBase64DecodingIgnoreUnknownCharacters into the options: parameter.

Resources