How to Autodetect & Convert a Document to a JPG Image Array using Go
While PNG images offer lossless compression capabilities, JPG still reigns supreme as the most commonly used & accepted image format on the web. As such, when we want to create image file versions of our documents, JPG format can’t be overlooked.
Our Document to JPG Array API makes it easy to convert dozens of Office and Image formats to JPG instantly (and at scale) by autodetecting your document type. Since JPG format can lose quality in its compression process, this API also offers the option to set the quality of your compression by entering an integer into the “quality” field (default is 75; 100 is highest quality, 1 is lowest quality). To take advantage of this API, all you need to do is follow instructions to structure your API call using ready-to-run Go code examples provided below. The best part: you can use it for free! You’ll just need to register a free account on our website (free accounts provide a limit of 800 API calls per month), which will provide you with an API key to enter within the appropriate header below.
To call the API, all we must do is include the below code examples in our file, configure our file path & API key inputs, and call the function:
package main
import (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {
url := "https://api.cloudmersive.com/convert/autodetect/to/jpg"
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("quality", "<integer>")
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))
}
After that, you’re all done — no more code examples required. Your JPG conversion needs are fulfilled!