Swift 3 base64编码图像用于上传

ada*_*ter 2 base64 uiimage swift3

我有一些很好的代码,允许我拍照和图像,然后在应用程序中显示它.我还将profilePic.image上传到我的数据库(作为一个blob),但我意识到这实际上并没有上传图像本身,只是关于图像的数据所以我无法渲染任何东西,因为没有任何东西可以解码.因此,我希望转换此函数以获取所选图像并将其编码为base64并使用相同的工作上载

func imagePickerController(
        _ selectImage: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [String : AnyObject])
    {
        let chosenImage = info[UIImagePickerControllerEditedImage] as! UIImage //2
        // imageByCroppingToRect()
        profilePic.contentMode = .scaleAspectFit //3
        profilePic.image = chosenImage //4
        dismiss(animated: true, completion: nil) //5
    }
Run Code Online (Sandbox Code Playgroud)

Jak*_*kub 9

您必须转换为UIImage您的网站可以读取的格式,例如jpeg,然后在base 64中编码.

let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = UIImageJPEGRepresentation(chosenImage, jpegCompressionQuality)?.base64EncodedString() {
    // Upload base64String to your database
}
Run Code Online (Sandbox Code Playgroud)

有关UIImageJPEGRepresentationData的信息,请参阅Apple文档