iOS: Convert UIImage to base64 without UIImageRepresentation - ios

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

Related

How to convert UIImage to base64 and POST to URL

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)

Converting from JSON string to UIImage always gives null?

I Get this kind of JSON:
NOTE: I put dots in "content" because it is too long byte array abd just to explain the situation.
{
"id":"53abc6a7975a9c10c292f670",
"nfcId":"testse",
"company":"TESt",
"qrId":"testvalue",
"address":"ajs;ldfh",
"mimeType":"IMAGE",
"url":"",
"content":"iVBORw0KGgoAAAANSUhEUgAA....."
}
And im trying to get this Json and diplay this information
the "content" field has a Byte array converted on the server from Image to byte array.
I use this code in xCode to convert those bytes to NSData, then to UIImage to be able to display it in UIImageView:
NSData *dataImage = [jsonArray[key] dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"data = %#", dataImage);
UIImage *img = [UIImage imageWithData:dataImage];
NSLog(#"img = %#", img);
The image is always gives me null.Although, data give me array of data.
I tried all kinds of encodings as a NSData parameters also:
dataUsingEncoding:NSASCIIStringEncoding
dataUsingEncoding:NSUTF8StringEncoding
dataUsingEncoding:NSUTF16StringEncoding
dataUsingEncoding:NSUTF32StringEncoding
I've used code like this before
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"data:image/png;base64,%#",jsonArray[key]]];
NSData *imageData = [NSData dataWithContentsOfURL:url];
UIImage *img = [UIImage imageWithData:imageData];
Note that initWithBase64EncodedString is only available from iOS7 onwards
I tried this code just right now and it works:
NSData* dataImage = [[NSData alloc] initWithBase64EncodedString:jsonArray[key] options:0];
UIImage *img = [UIImage imageWithData:dataImage];
The "content" encoded by Base64 String type.

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];

UIImage Object Not Formed Using NSData

I am getting the following response from a server:
{
"userId": "72e823ebc0c07fa99f279d6435e2c6ce",
"userHash": null,
"md5": "e993b7e9ec74bcdc1b1b7baec7d1cdd2",
"highres": null,
"thumbnail": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0
Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyADIDASIAAhEBAxEB/
8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2Jygg
kKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytL
T1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJ
BUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZa
XmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0CfRbZY3IzuAyOak0nTLOW0UzBt+e
cGpppcxvg87ajt76Cw0R7uVC3lgtj1rREMvtpVijo6q+5fu81Wu/EGmeFFMlwTiTkgHmnadqqanYwXqL5ayDIU9q8C8ceILq+8QXUU0haOFyqgelVo9xHu1v8U9BuLhIlM
g3fxHGBXWf2pYmAzLdRMgXdw4NfImmQXN1bNIHKQbsbj616DpdvcQ6RHsnLfNyc1jNpbGqi+p6+fHOmgkbJePaivMvN9jRWPOyuU6Rb9ZbaTyn3Ng4Feaaj48utIuNQ0
+6gaaOZNiKT/q/etvSPEEN1qr2dsoMAXcJMdTXJ61aaLe+K7v+2b1rSIAbSozmutbmD2Lnhzxvq2h26me1e6tZB+7JPCCuauBHqGvTXV04hjuHL4Pato+CdcvlWTSZGn0w/
wCpdmxkV01v8IIZbWOa51NhPtyybhhT6U7Kw07M56xvbGK3NpFGrpuyYx39627PXoJrmSwtYgFij35Hc+ldX4L8IDStMvoryxtpk2vtuHYbhxxXiVrcTaZ4gujAxk3uynJ6DN
YOkbqonY7I+KLgEj+zz+dFZWQeTIaKz9ia3j3I9F1+8e2ElrDArg5cnj5awdfli1PUJbqR/vDtWTBev9i+zKSOc5FUHDocFifxrpujiOoj8b6vDpkelQymOCIbUKNg4qEajrcoBW/
uMe8hrnIpPLmRm6A1urq8JRRtORTTBov2q+JtRlFtb6jcDdxgykA1txfC3xRBKks3kruIO5nxmsrRdVd7sKgwi/MD7ivZ/C+taV490waVq8rRX0XKurbQQOlS2UkcaPh5reB+
9tf+/gor0j/hVqZ4upsf9dDRSuOx8q2v3z9KJetFFBmyCTotSRfdNFFNF9Do/DvR/oa2vCrMPEdphiP346H3oopD6H1un+rX6CiiipGf/9k="
}
Thumbnail is a byte array and I want to convert that into NSData, then into an UIImage.
When I do the following, I end up with nil:
NSData *pictureData = [NSData dataWithBytes:[updatedData objectForKey:#"thumbnail"]];
UIImage *img = [[UIImage alloc] initWithData:pictureData];
How can I fix this?
This is not a "byte array". This is a NSString which contains a Base64 encoded image.
iOS7 has built in support for Base64 encoded data, for older versions you have to roll your own code. There are plenty of implementations available
This works on iOS7:
// NSString *base64String = [updatedData objectForKey:#"thumbnail"];
NSString *base64String = #"/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyADIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0CfRbZY3IzuAyOak0nTLOW0UzBt+ecGpppcxvg87ajt76Cw0R7uVC3lgtj1rREMvtpVijo6q+5fu81Wu/EGmeFFMlwTiTkgHmnadqqanYwXqL5ayDIU9q8C8ceILq+8QXUU0haOFyqgelVo9xHu1v8U9BuLhIlMg3fxHGBXWf2pYmAzLdRMgXdw4NfImmQXN1bNIHKQbsbj616DpdvcQ6RHsnLfNyc1jNpbGqi+p6+fHOmgkbJePaivMvN9jRWPOyuU6Rb9ZbaTyn3Ng4Feaaj48utIuNQ0+6gaaOZNiKT/q/etvSPEEN1qr2dsoMAXcJMdTXJ61aaLe+K7v+2b1rSIAbSozmutbmD2Lnhzxvq2h26me1e6tZB+7JPCCuauBHqGvTXV04hjuHL4Pato+CdcvlWTSZGn0w/wCpdmxkV01v8IIZbWOa51NhPtyybhhT6U7Kw07M56xvbGK3NpFGrpuyYx39627PXoJrmSwtYgFij35Hc+ldX4L8IDStMvoryxtpk2vtuHYbhxxXiVrcTaZ4gujAxk3uynJ6DNYOkbqonY7I+KLgEj+zz+dFZWQeTIaKz9ia3j3I9F1+8e2ElrDArg5cnj5awdfli1PUJbqR/vDtWTBev9i+zKSOc5FUHDocFifxrpujiOoj8b6vDpkelQymOCIbUKNg4qEajrcoBW/uMe8hrnIpPLmRm6A1urq8JRRtORTTBov2q+JtRlFtb6jcDdxgykA1txfC3xRBKks3kruIO5nxmsrRdVd7sKgwi/MD7ivZ/C+taV490waVq8rRX0XKurbQQOlS2UkcaPh5reB+9tf+/gor0j/hVqZ4upsf9dDRSuOx8q2v3z9KJetFFBmyCTotSRfdNFFNF9Do/DvR/oa2vCrMPEdphiP346H3oopD6H1un+rX6CiiipGf/9k=";
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *image = [UIImage imageWithData:data];
And that's your image:

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];

Resources