Home >Backend Development >Golang >Convert gif image to base64 in GO

Convert gif image to base64 in GO

WBOY
WBOYforward
2024-02-09 14:54:081031browse

Convert gif image to base64 in GO

In the GO language, converting GIF images to Base64 encoding is a common operation. By converting image data to Base64 encoding, we can easily embed images in web pages or transmit image data in string form. In the GO language, you can use the functions in the encoding/base64 package to achieve this conversion. This conversion is very simple and can be done with just a few lines of code. Below, I will introduce to you how to convert GIF images to Base64 encoding in GO language.

Question content

I'm trying to send a gif file via udp in go, I think the easiest way is to convert the gif image to base64 string and send it, but when I send the file When converting bytes to base64 it returns an empty string, I have tried the module "chilkat" using the following 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 it doesn't work, if anyone can help me

Solution

My solution is this:

var buff bytes.buffer
gif.encodeall(&buff, &anim)
based := base64.stdencoding.encodetostring(buff.bytes())

But the base64 string is obviously too long to send in udp, So the solution for correct sending 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"))

The above is the detailed content of Convert gif image to base64 in GO. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete