编码文件以发送到Google AutoML

I am writing a golang script to send an image to the prediction engine of Google AutoML API.

It accepts most files using the code below, but certain .jpeg or .jpeg it returns error 500 saying invalid file. Mostly it works, but I can't figure out the exceptions. They are perfectly valid jpg's.

I am encoding the payload using EncodeToString.

Among other things, I have tried decoding it, saving it to a PNG, nothing seems to work. It doesn't like some images.

I wonder if I have an error in my method? Any help would be really appreciated. Thanks

PS the file saves to the filesystem and uploads to S3 just fine. It's just the encoding to a string when it goes to Google that it fails.

imgFile, err := os.Open(filename)
if err != nil {
    fmt.Println(err)
}

img, fname, err := image.Decode(imgFile)
if err != nil {
    fmt.Println(fname)
}

buf := new(bytes.Buffer)
err = jpeg.Encode(buf, img, nil)

// Encode as base64.
imgBase64Str := base64.StdEncoding.EncodeToString(buf.Bytes())

defer imgFile.Close()

payload := fmt.Sprintf(`{"payload": {"image": {"imageBytes": "%v"},}}`, imgBase64Str)

// send as a byte
pay := bytes.NewBuffer([]byte(payload))
req, err := http.NewRequest(http.MethodPost, URL.String(), pay)

I believe I fixed it.

I looked in the Google docs again and for the speech to text (which is a different API) it says to do encode64 -w 0

So, looking in Go docs, it seems RawStdEncoding is right to use to replicate this behaviour, not StdEncoding

No image failures yet. Hope this helps someone else one day.