How to Convert a Video File to GIF in Go
2 min readJun 25, 2021
Thanks to innovations on both web and mobile devices, GIF files have become a household name. These short videos are designed to express an emotion or deliver a message that requires very little time investment. If you are looking to convert your video content to an animated GIF, you can use the following API in Go to instantly convert a wide range of video formats to GIF.
To call the function, simply input your video file into the below example code:
package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)func main() {url := "https://api.cloudmersive.com/video/convert/to/gif"
method := "POST"payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("inputFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)if err != nil {
fmt.Println(err)
return
}
req.Header.Add("fileUrl", "<string>")
req.Header.Add("maxWidth", "<integer>")
req.Header.Add("maxHeight", "<integer>")
req.Header.Add("preserveAspectRatio", "<boolean>")
req.Header.Add("frameRate", "<integer>")
req.Header.Add("startTime", "<dateTime>")
req.Header.Add("timeSpan", "<dateTime>")
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}
To further tailor the video conversion to your needs, you can input parameters such as max width, max height, frame rate, and more.