Convertir entre UIImage y cadena Base64

Resuelto changey asked hace 54 años • 24 respuestas

¿Alguien sabe cómo convertir UIImageuna cadena en Base64 y luego revertirla?

Tengo el siguiente código; la imagen original antes de codificarla es buena, pero solo obtengo una imagen en blanco después de codificarla y decodificarla.

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];
changey avatar Jan 01 '70 08:01 changey
Aceptado

Rápido

Primero necesitamos tener el NSData de la imagen.

//Use image name from bundle to create NSData
let image : UIImage = UIImage(named:"imageNameHere")!
//Now use image to create into NSData format
let imageData:NSData = UIImagePNGRepresentation(image)!

//OR next possibility

//Use image's path to create NSData
let url:NSURL = NSURL(string : "urlHere")!
//Now use image to create into NSData format
let imageData:NSData = NSData.init(contentsOfURL: url)!

Swift 2.0 > Codificación

let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)

Swift 2.0 > Decodificación

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)!

Swift 3.0 > Decodificación

let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!

Codificación :

let strBase64 = imageData.base64EncodedString(options: .lineLength64Characters)
print(strBase64)

Decodificación :

let dataDecoded:NSData = NSData(base64EncodedString: strBase64, options: NSDataBase64DecodingOptions(rawValue: 0))!
let decodedimage:UIImage = UIImage(data: dataDecoded)!
print(decodedimage)
yourImageView.image = decodedimage

Rápido 3.0

let dataDecoded : Data = Data(base64Encoded: strBase64, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImageView.image = decodedimage

C objetivo

iOS7 > versión

Puedes usarNSData's base64EncodedStringWithOptions

Codificación :

- (NSString *)encodeToBase64String:(UIImage *)image {
 return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

Decodificación :

- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
  NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
  return [UIImage imageWithData:data];
}

iOS 6.1 y <versión

Primera opción : use este enlace a encodeuna decodeimagen

Agregue la clase Base64 en su archivo project.

Codificación :

 NSData* data = UIImageJPEGRepresentation(yourImage, 1.0f);
 NSString *strEncoded = [Base64 encode:data];

Decodificación :

 NSData* data = [Base64 decode:strEncoded ];;
 image.image = [UIImage imageWithData:data];

Otra opción : utilizar QSUtilities para encodingydecoding


Paresh Navadiya avatar Jun 28 '2012 19:06 Paresh Navadiya

veloz 5

Codificación

func convertImageToBase64String (img: UIImage) -> String {
    return img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""
}

Descodificación

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data(base64Encoded: imageBase64String)
    let image = UIImage(data: imageData!)
    return image!
}

Nota: Probado en xcode 10.2

veloz 4

Codificación

func convertImageToBase64String (img: UIImage) -> String {
    let imageData:NSData = UIImageJPEGRepresentation(img, 0.50)! as NSData //UIImagePNGRepresentation(img)
    let imgString = imageData.base64EncodedString(options: .init(rawValue: 0))
    return imgString
}

Descodificación

func convertBase64StringToImage (imageBase64String:String) -> UIImage {
    let imageData = Data.init(base64Encoded: imageBase64String, options: .init(rawValue: 0))
    let image = UIImage(data: imageData!)
    return image
}

Nota: Probado en xcode 9.4.1

Vivek avatar Jul 18 '2018 05:07 Vivek

Método de extensión Swift 4.2

extension UIImage {
    func toBase64() -> String? {
        guard let imageData = self.pngData() else { return nil }
        return imageData.base64EncodedString(options: .lineLength64Characters)
    }
}

XCode 9.1 y Swift 4.0

//
// Convert UIImage to a base64 representation
//
class func convertImageToBase64(image: UIImage) -> String {
    let imageData = UIImagePNGRepresentation(image)!
    return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}

//
// Convert a base64 representation to a UIImage
//
class func convertBase64ToImage(imageString: String) -> UIImage {
    let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
    return UIImage(data: imageData)!
}
Soufiane ROCHDI avatar Dec 02 '2017 17:12 Soufiane ROCHDI

SWIFT 3.0, XCODE 8.0

Reemplace String con su URL. y testImage es una salida de ImageView

// Put Your Image URL
let url:NSURL = NSURL(string : "http://.jpg")!
// It Will turn Into Data
let imageData : NSData = NSData.init(contentsOf: url as URL)!
// Data Will Encode into Base64
let str64 = imageData.base64EncodedData(options: .lineLength64Characters)
// Now Base64 will Decode Here
let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)!
// turn  Decoded String into Data
let dataImage = UIImage(data: data as Data)
// pass the data image to image View.:)
testImage.image = dataImage

Espero que ayude gracias.

Avinash Mishra avatar Oct 19 '2016 06:10 Avinash Mishra