I am trying to send a gif file over UDP in go, the simplest method I think is to convert the gif image into a base64 string and send it, but when I convert the file bytes into base64 it returns an empty string, I've tried the module "chilkat" with this code :
bd := chilkat.NewBinData()
success := bd.LoadFile(path.Join(folderPath, "final.gif"))
if success != true {
panic("Fail!")
bd.DisposeBinData()
return
}
b64Data := *bd.GetEncoded("base64")
But its not working, if someone can help me
CodePudding user response:
I would recommend using the encoding/base64 package in the standard library.
You will most likely want to convert or append it into a []byte
slice that represents the UDP packet you want to send.
Here are some examples for encoding a file path or io.Reader
into a []byte
:
import (
"bytes"
"encoding/base64"
"io"
"os"
)
func EncodePath(path string) ([]byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
output := make([]byte, base64.StdEncoding.EncodedLen(len(data)))
base64.StdEncoding.Encode(output, data)
return output, nil
}
func EncodeReader(rd io.Reader) ([]byte, error) {
var b bytes.Buffer
enc := base64.NewEncoder(base64.StdEncoding, &b)
if _, err := io.Copy(enc, rd); err != nil {
return nil, err
}
if err := enc.Close(); err != nil {
return nil, err
}
return b.Bytes(), nil
}
CodePudding user response:
My solution was this:
var buff bytes.Buffer
gif.EncodeAll(&buff, &anim)
based := base64.StdEncoding.EncodeToString(buff.Bytes())
But the base64 string was clearly too long to be sent in UDP, so the solution do send it correctly is this:
encoded := recordScreenToGIF(seconds) // Record X seconds of screen, & convert the result into a base64 GIF
splited := SplitSubN(encoded, 10000) // Split "encoded" each 10K characters
conn.Write([]byte(strconv.Itoa(len(splited))))
for _, elm := range splited {
_, err = conn.Write([]byte(elm))
if err != nil {
panic(err)
}
time.Sleep(50 * time.Millisecond)
}
conn.Write([]byte("Done"))