Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 base64 encode image for upload

I have some nice code that allows me to pic and image and then display it in app. I was also uploading the profilePic.image to my database (as a blob) but I realised that this was not actually uploading the image itself but just data about the image so I could not render anything back as there was nothing to decode. So I want to transform this function to get the chosen image and encode it to base64 and utilise same working upload

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
    }
like image 492
adamprocter Avatar asked Apr 18 '26 12:04

adamprocter


2 Answers

You have to convert the UIImage to a format your website can read, e.g. jpeg before encoding it in 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
}

Note: In iOS 12 UIImageJPEGRepresentation was replaced by an instance method jpegData of UIImage:

let jpegCompressionQuality: CGFloat = 0.9 // Set this to whatever suits your purpose
if let base64String = chosenImage.jpegData(compressionQuality: jpegCompressionQuality)?.base64EncodedString() {
    // Upload base64String to your database
}

Refer to the Apple documentation for UIImageJPEGRepresentation and Data

like image 52
Jakub Avatar answered Apr 22 '26 00:04

Jakub


Data has a function to return a base64 representation of itself as another Data. No need to convert to String and back.

Take a look at the docs for Data.base64EncodedData()

if let data = UIImageJPEGRepresentation(photos, 0.5)?.base64EncodedData() {
    form.append(data, withName: "images", fileName: "photo.jpeg", mimeType: "image/jpeg")
}
like image 30
Fabian Avatar answered Apr 22 '26 00:04

Fabian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!