web-dev-qa-db-fra.com

Convertir entre les chaînes UIImage et Base64

Est-ce que quelqu'un sait comment convertir une UIImage en une chaîne Base64, puis l'inverser?

J'ai le code ci-dessous; l'image originale avant encodage est bonne, mais je n'obtiens une image vierge qu'après l'encodage et le décodage.

NSData *imageData = UIImagePNGRepresentation(viewImage);

NSString *b64EncStr = [self encode: imageData];

NSString *base64String = [self encodeBase64:imageData];
180
changey

Rapide

Nous avons d’abord besoin du NSData de l’image 

//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> Encodage

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

Swift 2.0> Décodage

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

Swift 3.0> Décodage

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

Encodage:

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

Décodage:

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

Swift 3.0

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

Objectif c

iOS7> version

Vous pouvez utiliser NSData'sbase64EncodedStringWithOptions

Encodage:

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

Décodage:

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

iOS 6.1 et <version

Première option: Utilisez this lien vers encode et decode image

Ajoutez Base64 class dans votre project

Encodage:

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

Décodage:

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

Une autre option: Utilisez QSUtilities pour encoding et decoding


525
Paresh Navadiya

Swift 3.0, XCODE 8.0

Remplacez String par votre URL. et testImage est un point de vente d'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

J'espère que ça aide Merci.

19
Avinash Mishra

Swift 4.2 Méthode d'extension

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

XCode 9.1 et 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)!
}
18
Souf R

Swift iOS8 

// prgm mark ---- 

// convert images into base64 and keep them into string

func convertImageToBase64(image: UIImage) -> String {

    var imageData = UIImagePNGRepresentation(image)
    let base64String = imageData.base64EncodedStringWithOptions(.allZeros)

    return base64String

}// end convertImageToBase64


// prgm mark ----

// convert images into base64 and keep them into string

func convertBase64ToImage(base64String: String) -> UIImage {

    let decodedData = NSData(base64EncodedString: base64String, options: NSDataBase64DecodingOptions(rawValue: 0) )

    var decodedimage = UIImage(data: decodedData!)

    return decodedimage!

}// end convertBase64ToImage
11
Vinod Joshi
@implementation UIImage (Extended)

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

@end
7
Peter Lapisu

Swift 3.0

Pour convertir une image en chaîne base64 

Testé en terrain de jeu

    var logo = UIImage(named: "image_logo")
    let imageData:Data =  UIImagePNGRepresentation(logo)
    let base64String = imageData.base64EncodedString()
    print(base64String)
7
dimo hamdy

Dans Swift 2.0, utilisez cette extension (crédit de Jonas Franz)

extension UIImage{
  func toBase64() -> String{
    let imageData = UIImagePNGRepresentation(self)!
    return imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
  }
}
6
Ciprian Rarau

Dans Swift 3.0 et Xcode 8.0

Encodage:

let userImage:UIImage = UIImage(named: "Your-Image_name")!
let imageData:NSData = UIImagePNGRepresentation(userImage)! as NSData
let dataImage = imageData.base64EncodedString(options: .lineLength64Characters)

Décodage:

let imageData = dataImage
let dataDecode:NSData = NSData(base64Encoded: imageData!, options:.ignoreUnknownCharacters)!
let avatarImage:UIImage = UIImage(data: dataDecode as Data)!
yourImageView.image = avatarImage
5
M.Nadeeshan

Swift 4

Encodage

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
}

Décodage

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

Note: Testé dans xcode 9.4.1

4
Vivek

Swift-Extension:

extension UIImage{
     func toBase64() -> String{
          var imageData = UIImagePNGRepresentation(self)
          return imageData.base64EncodedStringWithOptions(.allZeros)
     }
}
4
Jonas Franz
See my class -  AppExtension.Swift


// MARK: - UIImage (Base64 Encoding)

public enum ImageFormat {
    case PNG
    case JPEG(CGFloat)
}

extension UIImage {

    public func base64(format: ImageFormat) -> String {
        var imageData: NSData
        switch format {
        case .PNG: imageData = UIImagePNGRepresentation(self)
        case .JPEG(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }
        return imageData.base64EncodedStringWithOptions(.allZeros)
    }
}
1
A.G

Swift 4

enum ImageFormat {
    case png
    case jpeg(CGFloat)
}

extension UIImage {
    func base64(format: ImageFormat) -> String? {
        var imageData: Data?

        switch format {
        case .png: imageData = UIImagePNGRepresentation(self)
        case .jpeg(let compression): imageData = UIImageJPEGRepresentation(self, compression)
        }

        return imageData?.base64EncodedString()
    }
}

extension String {
    func imageFromBase64() -> UIImage? {
        guard let data = Data(base64Encoded: self) else { return nil }

        return UIImage(data: data)
    }
}
1
oscarr

Version Swift - Créer une base64 pour l'image

À mon avis, implicitement non emballé Facultatif en cas de UIImagePNGRepresenatation() n'est pas sûr, je vous recommande donc d'utiliser une extension comme ci-dessous:

extension UIImage {

    func toBase64() -> String? {
        let imageData = UIImagePNGRepresentation(self)
        return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
    }
}
1
lukszar

Swift 4.2 | Xcode 10

extension UIImage {

    /// EZSE: Returns base64 string
    public var base64: String {
        return self.jpegData(compressionQuality: 1.0)!.base64EncodedString()
    }
}
1
Ashish Kakkad

Dans Swift 3.0

func decodeBase64(toImage strEncodeData: String) -> UIImage {

    let dataDecoded  = NSData(base64Encoded: strEncodeData, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
    let image = UIImage(data: dataDecoded as Data)
    return image!

}
1

Pour iOS 7+, Objective-C, voici comment effectuer la conversion en commençant par une URL d'image:

NSURL *url = [NSURL URLWithString:self.groove.thumbnailURL];

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];

NSString *base64String = [UIImagePNGRepresentation(image)
base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
0
snibbe

Swift 4.2, Xcode 10.1

let imageData = UIImage (nommé: "imagename"). pngData ()?. base64EncodedString (options: .lineLength64Characters)

imprimer (imageData)

0
Kedar Sukerkar

Swift 3.0 et Xcode 8.0

let imageData = UIImageJPEGRepresentation(imageView.image!, 1)

    let base64String = (imageData! as Data).base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    print(base64String)
0
Amit Verma

J'ai essayé toutes les solutions, aucune n’a fonctionné pour moi (avec Swift 4), c’est la solution qui a fonctionné pour moi, si, à l’avenir, le même problème se posait.

let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options: 
 .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)

yourImage.image = decodedimage
0
Zubair