Return the Dominant Colors of the Image in Go
1 min readMar 22, 2022
Get key information about the dominant colors of an image with a simple API call. To take advantage of this API for your Go project, implement the below code from our API Console into your project and create a Cloudmersive account to receive the necessary API key (head to www.cloudmersive.com to take care of that).
package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)func main() {url := "https://api.cloudmersive.com/image/get-info/dominant-color"
method := "POST"payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("imageFile",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("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))
}
The top 5 dominant colors of the image will be returned in order of color dominance (example JSON response below):
{
"Successful": true,
"DominantColors": [
{
"R": 0,
"G": 0,
"B": 0
}
]
}