How to Identify Age from an Image in Go

Cloudmersive
2 min readAug 25, 2021

Determining the user demographics of your website can be incredibly helpful for crafting targeted marketing materials and campaigns. These demographics can be gathered in a number of ways, but one that is particularly simple is analyzing images uploaded by users to provide age data on each human face in the photo. The API solution we will be discussing in this article can be used in Go to automatically perform the age identification — individuals in the image don’t even need to be facing the camera for this function to work, which means you can use it on just about any photo containing a human face.

Let’s go ahead and call the function by inputting the image and our API key into the following code:

package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {url := "https://api.cloudmersive.com/image/face/detect-age"
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))
}

With this, you will receive data on the position of each face in the photo, along with an age approximation, age classification, and age confidence level. If you need to retrieve your API key, head over to the Cloudmersive website to register for a free account; this provides 800 monthly calls across all of our APIs.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.