To improve performance using the Anyline Cloud API, we have introduced an optional gzip compression method to enable faster file transfers (Post Request).
This Article will guide you on how to add this feature yourself to reduce the size of your images and make the most of our Cloud API.
PLEASE NOTE:
The implementation of this feature is not strictly limited to the following programming languages and code examples below. These examples are simply to demonstrate a variety of ways you could use this feature.
Option 1 - JavaScript
For the JavaScript Implementation, you will need to first install a 3rd party library to manage the compression of the images - our recommendation is Pako along with the gzip compression function included in the library.
Depending on your choice of package manager, use either one of the following commands to install Pako.
npm install pako
yarn add pako
Once you have the latest version of Pako included in your
package.json
file, import it and use it’s gzip function:
const pako = require('pako');
Inside your Post Request function, create a second variable to compress the payload using gzip like so:
const compressedData = pako.gzip(JSON.stringify(data));
Finally, include your selected content encoder (gzip) as a header inside the Post Request function like so:
headers: { ..., 'Content-Encoding': 'gzip', ..., }, ...
Below, you will see a JavaScript Example of a Post Request function with no image compression (LEFT) and the other including image compression (RIGHT).
const URL = 'https://api.anyline.com/v1/scan'; const IMG = 'base64String' const LICENSE = 'yourLicenseKey' const data = { config: { viewPlugin: { plugin: { meterPlugin: { scanMode: "AUTO_ANALOG_DIGITAL_METER" } } } }, license: LICENSE, blob: IMG }; function postRequest(){ fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } postRequest()
const pako = require('pako'); const URL = 'https://api.anyline.com/v1/scan'; const IMG = 'base64String' const LICENSE = 'yourLicenseKey' const data = { config: { viewPlugin: { plugin: { meterPlugin: { scanMode: "AUTO_ANALOG_DIGITAL_METER" } } } }, license: LICENSE, blob: IMG }; function postRequestGzip(){ // Compress payload using GZIP const compressedData = pako.gzip(JSON.stringify(data)); fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', }, body: compressedData }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } postRequestGzip()
// NON-COMPRESSED EXAMPLE const URL = 'https://api.anyline.com/v2/tiresidewall'; const IMG = 'base64string' const ACCESS_TOKEN = 'yourAccessToken' const data = { image: IMG, }; function postRequest(){ fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ACCESS_TOKEN}`, }, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } postRequest()
// COMPRESSED EXAMPLE const pako = require('pako'); const URL = 'https://api.anyline.com/v2/tiresidewall'; const IMG = 'base64string' const ACCESS_TOKEN = 'yourAccessToken' const data = { image: IMG, }; function postRequestGzip(){ // Compress payload using GZIP const compressedData = pako.gzip(JSON.stringify(data)); fetch(URL, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', 'Authorization': `Bearer ${ACCESS_TOKEN}`, }, body: compressedData }) .then(response => response.json()) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); } postRequestGzip()
Option 2 - Python
For the Python Implementation, you do not need to install any 3rd party library to manage the compression of the images.
Import gzip into your project using the following import statement:
import gzip
Include your selected content encoder (gzip) as a header inside the Post Request function like so:
headers: { ..., 'Content-Encoding': 'gzip', ..., }, ...
Finally, inside your Post Request function, create a variable to compress the payload using gzip like so:
compressed_data = gzip.compress(json.dumps(data).encode('utf-8'))
Below, you will see a Python Example of a Post Request function with no image compression (LEFT) and the other including image compression (RIGHT).
# NON-COMPRESSED EXAMPLE import requests import json import base64 URL = 'https://api.anyline.com/v1/scan' IMG = 'base64String' LICENSE = "yourLicenseKey" data = { "config": { "viewPlugin": { "plugin": { "meterPlugin": { "scanMode": "AUTO_ANALOG_DIGITAL_METER" } } } }, "license": LICENSE, "blob": IMG } def post_request(): headers = { 'Content-Type': 'application/json', } response = requests.post(URL, headers=headers, data=json.dumps(data)) try: response_data = response.json() print('Success:', response_data) except ValueError: print('Error: Invalid JSON response') post_request()
# COMPRESSED EXAMPLE import requests import json import gzip import base64 URL = 'https://api.anyline.com/v1/scan' IMG = 'base64String' LICENSE = "yourLicenseKey" data = { "config": { "viewPlugin": { "plugin": { "meterPlugin": { "scanMode": "AUTO_ANALOG_DIGITAL_METER" } } } }, "license": LICENSE, "blob": IMG } def post_request_gzip(): headers = { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', } # Compress payload using GZIP compressed_data = gzip.compress(json.dumps(data).encode('utf-8')) response = requests.post(URL, headers=headers, data=compressed_data) try: response_data = response.json() print('Success:', response_data) except ValueError: print('Error: Invalid JSON response') post_request_gzip()
# NON-COMPRESSED EXAMPLE import requests import json import base64 URL = 'https://api.anyline.com/v2/tiresidewall' IMG = 'base64string' ACCESS_TOKEN = "yourAccessToken" data = { "image": IMG } def post_request(): headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {ACCESS_TOKEN}' } response = requests.post(URL, headers=headers, data=json.dumps(data)) try: response_data = response.json() print('Success:', response_data) except ValueError: print('Error: Invalid JSON response') post_request()
# COMPRESSED EXAMPLE import requests import json import gzip import base64 URL = 'https://api.anyline.com/v2/tiresidewall' IMG = 'base64string' ACCESS_TOKEN = "yourAccessToken" data = { "image": IMG } def post_request_gzip(): headers = { 'Content-Type': 'application/json', 'Content-Encoding': 'gzip', 'Authorization': f'Bearer {ACCESS_TOKEN}' } # Compress payload using GZIP compressed_data = gzip.compress(json.dumps(data).encode('utf-8')) response = requests.post(URL, headers=headers, data=compressed_data) try: response_data = response.json() print('Success:', response_data) except ValueError: print('Error: Invalid JSON response') post_request_gzip()
Option 3 - Java
For the Java Implementation, you do not need to install any 3rd party library to manage the compression of the images. You can use the
GZIPOutputStream
class included in thejava.util
library.Import gzip into your project using the following import statement:
import java.util.zip.GZIPOutputStream;
Create a new instance of the
GZIPOutputStream
class that wraps around theByteArrayOutputStream
instance. Then, write the Post Request Data to the newGZIPOutputStream
instance and convert it to a byte array like so:
ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) { gzipOut.write(postData); } byte[] compressedData = baos.toByteArray();
Finally, inside your
HttpRequest
, include your selected content encoder (gzip) as a header and be sure to post the compressed data like so:
HttpRequest request = HttpRequest.newBuilder() ... ... .header("Content-Encoding", "gzip") ... .POST(HttpRequest.BodyPublishers.ofByteArray(compressedData)) ...;
Below, you will see a Java Example of a Post Request function with no image compression (LEFT) and the other including image compression (RIGHT).
// NON-COMPRESSED EXAMPLE import java.io.*; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; public class Example { private static final String URL = "https://api.anyline.com/v1/scan"; private static final String IMG = "base64String"; private static final String LICENSE = "yourLicenseKey"; public static void postRequest() throws IOException, InterruptedException { String jsonPayload = "{" + "\"config\": {" + "\"viewPlugin\": {" + "\"plugin\": {" + "\"meterPlugin\": {" + "\"scanMode\": \"AUTO_ANALOG_DIGITAL_METER\"" + "}" + "}" + "}" + "}," + "\"license\": \"" + LICENSE + "\"," + "\"blob\": \"" + IMG + "\"" + "}"; byte[] postData = jsonPayload.getBytes(StandardCharsets.UTF_8); HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(URL)) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofByteArray(postData)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Success: " + response.body()); } public static void main(String[] args) { try { postRequest(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
// COMPRESSED EXAMPLE import java.io.*; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import java.util.zip.GZIPOutputStream; public class Example { private static final String URL = "https://api.anyline.com/v1/scan"; private static final String IMG = "base64String"; private static final String LICENSE = "yourLicenseKey"; public static void postRequestGzip() throws IOException, InterruptedException { String jsonPayload = "{" + "\"config\": {" + "\"viewPlugin\": {" + "\"plugin\": {" + "\"meterPlugin\": {" + "\"scanMode\": \"AUTO_ANALOG_DIGITAL_METER\"" + "}" + "}" + "}" + "}," + "\"license\": \"" + LICENSE + "\"," + "\"blob\": \"" + IMG + "\"" + "}"; byte[] postData = jsonPayload.getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) { gzipOut.write(postData); } byte[] compressedData = baos.toByteArray(); HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(URL)) .header("Content-Type", "application/json") .header("Content-Encoding", "gzip") .POST(HttpRequest.BodyPublishers.ofByteArray(compressedData)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Success: " + response.body()); } public static void main(String[] args) { try { postRequestGzip(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
// NON-COMPRESSED EXAMPLE import java.io.*; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; public class Example { private static final String URL = "https://api.anyline.com/v2/tiresidewall"; private static final String IMG = "base64string"; private static final String ACCESS_TOKEN = "yourAccessToken"; public static void postRequest() throws IOException, InterruptedException { String jsonPayload = "{\"image\":\"" + IMG + "\"}"; byte[] postData = jsonPayload.getBytes(StandardCharsets.UTF_8); HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(URL)) .header("Content-Type", "application/json") .header("Authorization", "Bearer " + ACCESS_TOKEN) .POST(HttpRequest.BodyPublishers.ofByteArray(postData)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Success: " + response.body()); } public static void main(String[] args) { try { postRequest(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
// COMPRESSED EXAMPLE import java.io.*; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.concurrent.CompletableFuture; import java.util.zip.GZIPOutputStream; public class Example { private static final String URL = "https://api.anyline.com/v2/tiresidewall"; private static final String IMG = "base64string"; private static final String ACCESS_TOKEN = "yourAccessToken"; public static void postRequestGzip() throws IOException, InterruptedException { String jsonPayload = "{\"image\":\"" + IMG + "\"}"; byte[] postData = jsonPayload.getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (GZIPOutputStream gzipOut = new GZIPOutputStream(baos)) { gzipOut.write(postData); } byte[] compressedData = baos.toByteArray(); HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(URL)) .header("Content-Type", "application/json") .header("Content-Encoding", "gzip") .header("Authorization", "Bearer " + ACCESS_TOKEN) .POST(HttpRequest.BodyPublishers.ofByteArray(compressedData)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Success: " + response.body()); } public static void main(String[] args) { try { postRequestGzip(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
Final Notes
Please be sure to add the following to any of the code examples:
Replace
“base64String"
with your actual base 64 Image String inside theIMG
variable.Replace
“yourAccessToken"
with your actual Access Token inside theACCESS_TOKEN
variable.