Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage to base64 String Encoding

How to convert UIimage to base64 encoded string? I couldn't find any examples or codes with detailed regarding.

like image 622
apple Avatar asked Oct 08 '10 09:10

apple


6 Answers

I wonder why didn't you find your question because it's a very old question & can be found here.

Anyways, You need to first add NSData categories to your project which are available from here -

header and implementation Then convert your UIImage object into NSData the following way:

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

And then apply Base64 encoding to convert it into a base64 encoded string:

NSString *encodedString = [imageData base64Encoding];
like image 98
Sagar Avatar answered Oct 14 '22 08:10

Sagar


There are changes in iOS 7 that allow this to be done without using any external categories to support Base64 encoding/decoding.

You could just write it directly using:

- (NSString *)base64String {
    return [UIImagePNGRepresentation(self) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
like image 38
Abizern Avatar answered Oct 14 '22 06:10

Abizern


You can follow below code

-(NSString *)imageToNSString:(UIImage *)image
{
NSData *imageData = UIImagePNGRepresentation(image);
    return [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

-(UIImage *)stringToUIImage:(NSString *)string
{
 NSData *data = [[NSData alloc]initWithBase64EncodedString:string
                                                     options:NSDataBase64DecodingIgnoreUnknownCharacters];
    return [UIImage imageWithData:data];
}
like image 39
Bhat Avatar answered Oct 14 '22 07:10

Bhat


@implementation UIImage (Extended)

- (NSString *)base64String {
    NSData * data = [UIImagePNGRepresentation(self) base64EncodedDataWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return [NSString stringWithUTF8String:[data bytes]];
}

@end
like image 35
Peter Lapisu Avatar answered Oct 14 '22 07:10

Peter Lapisu


NSData (Base64) has changed slightly since the last reply in this thread.

you should now use:

NSData *base64EncodedImage = [UIImageJPEGRepresentation(img, 0.8) base64EncodingWithLineLength:0];
like image 25
Fabio Napodano Avatar answered Oct 14 '22 07:10

Fabio Napodano


Swift 3

I use base64EncodedString() to convert Data() object to base64 string

To convert image to base64 string

    var sample = UIImage(named: "image_logo")
    let imageData:Data =  UIImagePNGRepresentation(sample!)!
    let base64String = imageData.base64EncodedString()
like image 26
dimohamdy Avatar answered Oct 14 '22 06:10

dimohamdy