Getting Corrupt Base64 Encoded Image - ios

I have tried google and stackoverflow but not able to get a satisfactory answer I am a newbie and trying to encode image send/upload to server then decode same image in base64 image and show in my collectionview's Cell's imageview.
I have encoded the image in base64 successfully, I have checked the encoded string in online base64 formatter and getting my image in output so my encoding is working fine.
2 Getting the below error while decoding.....
<Error>: ImageIO: JPEG Unsupported marker type 0x6c
<Error>: ImageIO: JPEG Corrupt JPEG data: 1 extraneous bytes before marker 0x6c
I am using the below code to decode the image
NSString *imageURL = [imagename objectAtIndex:indexPath.row];
NSData *imageData = [Base64 decode:imageURL];
ImageView.image = [UIImage imageWithData:imageData];
Any Suggestion and Advice will be appreciated....

Try this...
NSString *imageString = [imagename objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"data:image/png;base64,%#",imageString]];
NSData *imageData = [NSData dataWithContentsOfURL:url];
ImageView.image = [UIImage imageWithData:imageData];

Related

function to duplicate images for thumbnail?

I'm making a photo gallery app.
I'm compressing the images
NSData *imageData = UIImageJPEGRepresentation(image,0.5)
and then want to create a duplicate (for thumbnails) that I'll compress even further
NSData *imageData = UIImageJPEGRepresentation(image,0.2)
I'm a little stuck on the middle step of how to create a duplicate, anyone know if there is a function for this?
Probably you can convert NSData to UIImage.
Swift3:
let imageData = UIImageJPEGRepresentation(thumbImage,0.5)
let thumbImage = UIImage(data:UIImageJPEGRepresentation(UIImage(data: imageData),0.2))
Objective C:
NSData *imageData = UIImageJPEGRepresentation(image,0.5)
UIImage *thumb = [UIImage imageWithData: UIImageJPEGRepresentation([UIImage imageWithData: imageData],0.5)];

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

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.

UIImage Object Not Formed Using NSData

I am getting the following response from a server:
{
"userId": "72e823ebc0c07fa99f279d6435e2c6ce",
"userHash": null,
"md5": "e993b7e9ec74bcdc1b1b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bsbj616DpdvcQ6RHsnLfNyc1jNpbGqi+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/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKD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aaLe+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