简体   繁体   中英

Base64 encoding with Swift 3

How do you encode an image to base64 in Swift 3.0?

I tried to do it this way:

let imageData = UIImageJPEGRepresentation(globalImage!, 75)
let string64 = imageData!.base64EncodedString()

where globalImage is my image. I successfully sent the data to my web server but when I try to load the image it's not in a form that my computer can recognize.

Here are the encoding and decoding methods.

func encodeImageToBase64(image : UIImage) -> String{

   let imageData : Data = UIImagePNGRepresentation(image)! as Data
   let strBase64 = imageData.base64EncodedString(options: Data.Base64EncodingOptions.init(rawValue: 0))
   return strBase64
}

func decodeBase64ToImage(base64 : String) -> UIImage{

    let dataDecoded : NSData = NSData(base64Encoded: base64, options: NSData.Base64DecodingOptions(rawValue: 0))!
    let decodedimage : UIImage = UIImage(data: dataDecoded as Data)!
    return decodedimage
}

你的第二个参数是75,它应该是0.7

let imageData = UIImageJPEGRepresentation(globalImage!, 0.7)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM