How to Crop an Image to a Rectangular Area: Use the Cloudmersive Image API in Go

Processing images manually is impractical at scale. Thankfully, that’s when our Image API does its best work. With our Square Face Crop iteration, you can simplify the process of cropping a specific square region from an image by inputting pixel values (left, top, width, & height). Take advantage of this API with ready-to-run code samples below in Go:

package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {url := "https://api.cloudmersive.com/image/edit/crop/rectangle/%3Cinteger%3E/%3Cinteger%3E/%3Cinteger%3E/%3Cinteger%3E"
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))
}

Cropping headshot photos for a website? On our Cloudmersive API Console page, you’ll find another iteration of our Image API which uses machine learning to find a face in an image crop a square around that face. When you navigate to the Console page, select “Image API” from the “Select a Spec” dropdown menu and navigate to the “Face” category below.

In either case, you’ll need a Cloudmersive API key to connect. To get one, you can make a free account on our website (www.cloudmersive.com) with a limit of 800 API calls per month, or select another one of our account options.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cloudmersive

Cloudmersive

437 Followers

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