Swift + gpt-4-vision-preview API Base64 Imag error, unsupported image

I am tring to upload image to gpt4 vision ,but get error
" You uploaded an unsupported image. Please make sure your image is below 20 MB in size and is of one the following formats: ['png', 'jpeg', 'gif', 'webp']"

  • my image procession logic here: actual size of image in KB: %f 950.822
extension UIImage {
    var base64: String? {
        self.jpegData(compressionQuality: 0.0)?.base64EncodedString()
var base64 = image.base64
let imgData = NSData(data: image.jpegData(compressionQuality: 1)!)
var imageSize: Int = imgData.count
print("actual size of image in KB: %f ", Double(imageSize) / 1000.0)
  • my api calling like this
        private let baseUrl = "https://api.openai.com/v1/chat/completions"
        let headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Authorization":  "Bearer \(apiToken)"
        let payload = [
            "model": "gpt-4-vision-preview",
            "messages": [
                "role": "user",
                "content": [
                    "type": "text",
                    "text": "What’s in this image?"
                    "type": "image_url",
                    "image_url": [
                        "url": "data:image/jpeg;base64,\(base64)",
                        "detail": "low"
        ] as! [String : Any]
                   method: .post,
                   parameters: payload,
                   encoding: JSONEncoding.default,
                   headers: headers
        ).responseString { data in

As a quick sanity check, pass an actual valid image url in there and see if it returns ok. I can only imagine there is something in there turning the 64 encoded string into an format it does not understand, maybe also try not using maximum compression, 0 might have some odd effect.

1 Like

Thanks for your advice, yes swift add a ‘optional’ in base 64 formating…, now it works!

1 Like