How to convert UIImage to base64 and POST to URL - ios

I'm having difficult with converting an image to base64 and then posting it to a server, where I will receive a number in return. I am using objective c.
Any ideas? I've tried a couple of things but I always get a thread error when trying to set certain NSDictionary parameters.

Convert UIImage in base64
NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1.0);
NSString *base64String = [imageData base64EncodedStringWithOptions:kNilOptions];
NSString *encodedString2 = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)base64String, NULL, CFSTR("!*'();:#&=+$,/?%#[]\" "), kCFStringEncodingUTF8));
send this string using normal way and post on server. Also need to minor changes on your server to getting this image.

Convert UIImage to base64 string For Objective c
NSData *imageData = UIImageJPEGRepresentation(_profileImgObj.image, 1.0);
NSString *base64Img = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
For Swift
let Imagedata = UIImageJPEGRepresentation(_profileImgObj.image, 0.5)
let strBase64Image = Imagedata!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())

Heres how I do it with Swift:
let data = UIImageJPEGRepresentation(image, 0.5)
let imageString = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)

Related

iOS: Convert UIImage to base64 without UIImageRepresentation

I think everything is in the title:
I have a UIImage that I need to convert to base64 without using UIImagePNGRepresentation or UIImageJPEGRepresentation. Objective C is what I code in.
Is this possible?
When converting to base64 string:
NSData *imageBase64Data = [ImageData base64EncodedDataWithOptions:0];
NSString *imageBase64String = [[NSString alloc] initWithData:imageBase64Data encoding: NSUTF8StringEncoding];
And converting it back:
NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0];
UIImage *image = [UIImage imageWithData:data];
as you can see from the code, we just converted the string back to data(originally image)
Convert the image to NSData without assigning a png or jpg representation like this:
CGDataProviderRef provider = CGImageGetDataProvider(image.CGImage);
NSData* data = (id)CFBridgingRelease(CGDataProviderCopyData(provider));
Then convert the data to a base64 string using a library like this one: https://github.com/ekscrypto/Base64

How to loop to retrieve images from web with NSData where an array holds url strings?

using URL in objective C is always misleading. Percent Encoding works in one situation and not in another. I just can't get why its so difficult to work with URL in objective C when other languages like C# never complain about such matters.
[NSData dataWithContentOfURL:] retrieves image if url is hard-coded, but not when it is provided from some variable that is retrieved at runtime. Percent Encoding is not working here. Whats the best way to handle URL in dynamic situation like this and others too?
NSString *logoString = [feeds[indexPath.row] objectForKey:#"logo"];
NSURL *logoURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#",logoString]];
NSData *logoData = [NSData dataWithContentsOfURL:logoURL];
UIImage *logoImage = [UIImage imageWithData:logoData];
imageView.image = logoImage;
percent encoding code:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)#"!*'();:#&=+$,/?%#[]",
kCFStringEncodingUTF8 );

Base64 encoded string wont decode (iOS)

I am base64 encoding some data using the following line:
NSString *theData = [serialized base64EncodedStringWithOptions:kNilOptions];
This works correctly and I then pass this string to my web server which stores it in the database.
Later, I am then retrieving this base64 encoded string back from the web server which also works correctly (I have compared both the original before upload and the after download strings and they are the same).
However, when I try to decode this string using:
NSString *theString = [imageDict objectForKey:#"image"];
NSData *imageData = [[NSData alloc] initWithBase64EncodedString:theString
options:kNilOptions];
it just gives me a null value for imageData.
If I output theString it is the correct base64 encoded string I uploaded.
Any ideas why it won't decode?
Thanks in advance.
I used NSDataAdditions.h < see http://code.ohloh.net/file?fid=28qaXmo6xH1Z4clfmn9_wJqDqNI&cid=xVjpNPxNo_A&s=&fp=308694&mp=&projSelected=true#L0 and for .m http://code.ohloh.net/file?fid=tXQCCVHemN1iAx6ZQSy1VkBACXA&cid=xVjpNPxNo_A&s=&fp=308694&mp&projSelected=true#L0 >
NSData *imageData = [NSData dataWithBase64EncodedString:theString];

Save and load image from SQL database

I'm trying to display an image from my Database.
This part works nicely.
I save the image in the DB like this :
UIImage *resizedImg = [Generics scaleImage:self.photo.image toResolution:self.photo.frame.size.width and:self.photo.frame.size.height];
NSData *imgData = UIImageJPEGRepresentation(resizedImg, 0.9);
NSString *stringDataImage = [NSString stringWithFormat:#"%#",imgData];
[dict setObject:stringDataImage for key#"image"];
// POST Request to save the image in DB ...
Now when I try to load the image and set it into my UIImageView I do this way :
NSData *data = [[[MyUser sharedUser] picture] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
Or
NSData *data = [[[MyUser sharedUser] picture] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
self.imageView.image = [UIImage withData:data];
But this doesn't work.
data is not equal to imgData, I think it's the encoding but I can find the good one.
And [UIImage withData:data] return nil;
Can you help me?
EDIT :
Convert and save
UIImage *resizedImg = [Generics scaleImage:self.photo.image toResolution:self.photo.frame.size.width and:self.photo.frame.size.height];
NSData *imgData = UIImageJPEGRepresentation(resizedImg, 0.9);
[dict setObject:[imgData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength] forKey:#"image"];
Load the image
NSData *data = [[NSData alloc] initWithBase64EncodedData:[[MyUser sharedUser] picture] options:kNilOptions];
NSLog(#"%#", data);
self.image.image = [UIImage imageWithData:data];
You are converting the NSData to a string and saving that to your database. Two issues:
Your choice of using the stringWithFormat construct is an inefficient string representation of your data (resulting in string representation that is roughly twice the size). You probably want to use base64 (for which the string representation is only 33% larger).
You are saving your string representation, but never converting it back to binary format after retrieving it. You could write a routine to do this, but it's better to just use established base64 formats.
If you want to save the image as a string in your database, you should use base64. Historically we would have directed you to one of the many third party libraries (see How do I do base64 encoding on iphone-sdk?) for converting from binary data to base64 string (and back), or, iOS 7 now has native base 64 encoding (and exposes the private iOS 4 method, in case you need to support earlier versions of iOS).
Thus to convert NSData to NSString base64 representation:
NSString *string;
if ([data respondsToSelector:#selector(base64EncodedStringWithOptions:)]) {
string = [data base64EncodedStringWithOptions:kNilOptions]; // iOS 7+
} else {
string = [data base64Encoding]; // pre iOS7
}
And to convert base64 string back to NSData:
NSData *data;
if ([NSData instancesRespondToSelector:#selector(initWithBase64EncodedString:options:)]) {
data = [[NSData alloc] initWithBase64EncodedString:string options:kNilOptions]; // iOS 7+
} else {
data = [[NSData alloc] initWithBase64Encoding:string]; // pre iOS7
}
If you really want to turn binary data into a string you should be using base64 encoding. Luckily for you, NSData now supports Base64 natively
So you could get your string from data with:
NSString *stringDataImage = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
And you could turn this back into NSData with:
NSData *imgData = [[NSData alloc] initWithBase64EncodedString:stringDataImage options:kNilOptions];

How to disable or bypass escape sequence in iOS string for Base64 Image url data

I am receiving base64 strings from a json request from my server...
The base64 strings look like this:
"/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1J..." (well shortened)
Now my problem is that when I turn this from the NSString > NSURL, the backslashes escape from the string...
"/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1J"
i.e. "/" turns into just "/"
Now I'm pretty sure that this is the problem for my encoding to a UIImage problems (going through the following method: NSString -> NSURL -> NSData -> UIImage)
Code to create UIImage:
imageAllArray = [pathwayResults valueForKey:#"images_data_base64"];
NSURL *image2URL = [NSURL URLWithString:[imageAllArray objectAtIndex:1]];
NSData *image2Data = [NSData dataWithContentsOfURL:image2URL];
imageTwo = [UIImage imageWithData:image2Data];
Does anyone know a way to ensure that the backslashes stay within the string to convert?
Or is there another/easier way to go about this?
NSString *encodedString = [#"your string" stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I found that the backslashes weren't doing much harm at all and that it was because I forgot to prepend the string with: "data:image/png;base64,"
See below:
NSString *prepender = #"data:image/png;base64,";
NSString *image1String = [NSString stringWithFormat:#"%#%#", prepender, [pathwayImageArray objectAtIndex:0]];
NSURL *image1URL = [NSURL URLWithString:image1String];
NSData *image1Data = [NSData dataWithContentsOfURL:image1URL];
imageOne = [UIImage imageWithData:image1Data];
Hope this helps someone else!

Resources