I am trying to convert media files in my IOS app to base 64 encoded strings. When I convert an image, I successfully see the encoded string on the console.
NSData *videoData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"photo" ofType:#"jpg"]];
NSString *base64Encoded = [videoData base64EncodedStringWithOptions:0];
NSLog(#"%#", base64Encoded);
But when I try to give a .mov file, it does not print anything.
NSData *videoData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"movie" ofType:#"mov"]];
Can someone please tell me what is that I am doing wrong? Or how can I convert .mov file to base64 encoded string?
Thanks
Check the below link and you will be able to find the solution.
http://cocoadev.com/BaseSixtyFour
Related
I need to download pdf file which I get in api response as a base64string.
How should I save it locally based on cell tag and preview it using documentcontroller?
Eg-api response is an array of dictionaries with different pdf files where we have a key called "pdf":"zcvffaewww.."
I need to download these pdf files on tap of uibutton on uitableviewcell and preview it in documentcontroller.
Please help.
Thanks.
you are getting a base64 string in JSON, it means you are getting the file name and file type also right (if not getting then it is fine)
Step 1: Instead of download, you can view that PDF in webView. Here is the way to do this,
// convert your base64 string into NSData
NSData* myData = [NSData dataFromBase64String: yourBase64String];
then write below code to show pdf in webView,
[_webView loadData:myData
MIMEType:#"application/pdf"
textEncodingName:#"NSUTF8StringEncoding"
baseURL:[NSURL URLWithString:#"https://www.google.co.in/"]];
// zooming pdf view
_webView.scalesPageToFit = YES;
_webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
It will show pdf in webView
step 2: for downloading pdf, write code
NSURL *URL = [NSURL URLWithString:
[NSString stringWithFormat:#"data:application/pdf;base64,%#",
numStr]];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"filename.pdf"];
[urlData writeToFile:filePath atomically:YES];
}
I have video data,
I need to convert the data into '.h264' format and save into a Temporary file.
NSString* filename = [NSString stringWithFormat:#"capture.h264"];
NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
NSURL* url = [NSURL fileURLWithPath:path];
I have created the temporary file path but, how can I attach the data along with the file and save.
Editted:
Sorry.
I was my mistake. self answering.
NSData *data = [[NSData alloc]initWithBase64EncodedString:val options:0];
NSString* filename = [NSString stringWithFormat:#"capture.h264"];
NSString* htmlFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];
[data writeToFile:htmlFilePath atomically:YES];
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
I am using vector graphics in my application and want to store some on Parse.com. I need to first convert these to NSData before upload. Is it possible to convert a pdf file to NSData?
UIImage *image = [UIImage imageNamed:#"coolImage.pdf"];
NSData *data = UIImageJPEGRepresentation(image);
I know NSData allows for a jpg of png representation but what about pdfs? Any tips on this would be greatly appreciated!
//to convert pdf to NSData
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:#"test.pdf"];
NSData *myData = [NSData dataWithContentsOfFile:pdfPath];
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]];