2

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
    }

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

1

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")
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.