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.
Related
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];
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
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];
I have fetched data from sqlite database using CoreData, and got NSString value:
"SxzYEWe6vE2ggLy5k9XV0Q24QJoOfvrHt9jCpq8CgCkGvfdgghjPIhDH0qZkNXjSHQJEw0cbGzFEoqZSIpImoqcuc8iA57oRne31fxgigPLWiAyAjjNnam68Z25hArGzDXudEA1AXoSM1TmlLMSV6c3XfDZM/IPPR245K5+DawOH5M8ZdUnbDyqVKRsi6KvqKou7mVA8DoZWrPBgN5YbvVC/da0F9QHCcq8Di8dNQ2/sf/oVs/A+ThHnglkscKyFuQ3FH+HNjENG2ZHtyWe1fQ=="
It seemed to be a base64 encoded string. I tried many ways to decode the string using:
NSData *dataString = [[NSData alloc] initWithBase64EncodedString:data.desc options:0];
NSString *textMeaning = [[NSString alloc] initWithData:dataString encoding:NSUTF8StringEncoding];
// textMeaning return (null).
has anyone seen this encoded string before and know how to decode it?
Try this base64 method to decode,
NSString *decodeString = #"Apple";
//Encode String
NSData *encodeData = [decodeString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [encodeData base64EncodedStringWithOptions:0];
NSLog(#"Encoded String Value: %#", base64String);
//Decode String
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(#"Decoded String Value: %#", decodedString);
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.