Image standard
Formats and size
- PDF*, JPG, PNG, WebP or GIF. *Only the first page of a PDF is read.
- Up to 10 MB per file. The whole request, with the image in base64, goes up to 15 MB; over that, the answer is 413.
- The file's type is read from the file itself, not from its extension or name.
Our standard: 1344 to 2048 px on the long side
The engines read an image best at 1344 to 2048 px on its long side; on an A4 scan, that is about 120 to 175 DPI. An image outside the standard is refused with 422, with IMAGE_RESOLUTION_TOO_LOW or IMAGE_RESOLUTION_TOO_HIGH, at no charge.
resizeImage
With "resizeImage": true, an image outside the standard is resized on our side instead of refused, for 1 extra credit; on the standard engines, the request needs 2 credits available. An image within the standard is never resized. When the image was resized, the answer carries imageResized: true and the sizes before and after.
bash
#!/usr/bin/env bash
# Extract an image outside our standard: resizeImage brings it to the
# standard first, for one extra credit (the 800x640 sample is too small).
# Needs DOCSOCR_API_KEY in the environment.
set -euo pipefail
REQUEST_ID="resize-$(date +%s)-$RANDOM" # one id per document
# The API answers within 90 s
curl -sS --max-time 120 https://api.docsocr.com/api/v1/documents/birth-certificate \
-H "Authorization: Bearer $DOCSOCR_API_KEY" \
-H "Content-Type: application/json" \
--data-binary @- <<EOF
{
"imageType": "url",
"imageUrl": "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
"requestId": "$REQUEST_ID",
"resizeImage": true
}
EOFpy
"""Extract an image outside our standard: resizeImage brings it to the
standard first, for one extra credit (the 800x640 sample is too small).
Needs the requests package and DOCSOCR_API_KEY in the environment.
"""
import os
import uuid
import requests
response = requests.post(
"https://api.docsocr.com/api/v1/documents/birth-certificate",
headers={"Authorization": f"Bearer {os.environ['DOCSOCR_API_KEY']}"},
json={
"imageType": "url",
"imageUrl": "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
"requestId": str(uuid.uuid4()), # one id per document
"resizeImage": True,
},
timeout=120, # above the API's 90 s extraction budget
)
answer = response.json()
if response.status_code != 201 or not answer["success"]:
raise SystemExit(f"{response.status_code} {answer.get('errorCode', '')} {answer.get('message') or answer.get('error')}")
print(answer["data"]["dados_pessoais"]["nome_completo"])
print("resized:", answer.get("imageResized", False), "credits:", answer["creditsCharged"])js
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'
const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
imageType: 'url',
imageUrl: 'https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg',
requestId: randomUUID(), // one id per document
resizeImage: true,
}),
signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
process.exit(1)
}
console.log(answer.data.dados_pessoais.nome_completo)
console.log('resized:', answer.imageResized ?? false, 'credits:', answer.creditsCharged)php
<?php
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs the curl extension and DOCSOCR_API_KEY in the environment.
$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'imageType' => 'url',
'imageUrl' => 'https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg',
'requestId' => bin2hex(random_bytes(16)), // one id per document
'resizeImage' => true,
]),
]);
$body = curl_exec($request);
if ($body === false) {
fwrite(STDERR, curl_error($request) . PHP_EOL);
exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;
echo 'resized: ', var_export($answer['imageResized'] ?? false, true), ' credits: ', $answer['creditsCharged'], PHP_EOL;java
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs Java 17+ and DOCSOCR_API_KEY in the environment. Run: java Resize.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.UUID;
public class Resize {
public static void main(String[] args) throws Exception {
String body = """
{
"imageType": "url",
"imageUrl": "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
"requestId": "%s",
"resizeImage": true
}""".formatted(UUID.randomUUID()); // one id per document
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.docsocr.com/api/v1/documents/birth-certificate"))
.timeout(Duration.ofSeconds(120)) // above the API's 90 s extraction budget
.header("Authorization", "Bearer " + System.getenv("DOCSOCR_API_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
// The answer is JSON: data, imageResized and creditsCharged; read them with your JSON library
System.out.println(response.body());
if (response.statusCode() != 201 || !response.body().contains("\"success\":true")) {
System.exit(1);
}
}
}csharp
// Extract an image outside our standard: resizeImage brings it to the
// standard first, for one extra credit (the 800x640 sample is too small).
// Needs .NET 8+ and DOCSOCR_API_KEY in the environment. Run: dotnet run Resize.cs (.NET 10)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(120) }; // above the API's 90 s extraction budget
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DOCSOCR_API_KEY"));
var body = new JsonObject
{
["imageType"] = "url",
["imageUrl"] = "https://docsocr.com/samples/certidao-nascimento-exemplo-800x640.jpg",
["requestId"] = Guid.NewGuid().ToString(), // one id per document
["resizeImage"] = true,
};
using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
using var response = await http.PostAsync("https://api.docsocr.com/api/v1/documents/birth-certificate", content);
using var answer = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = answer.RootElement;
if ((int)response.StatusCode != 201 || !root.GetProperty("success").GetBoolean())
{
Console.Error.WriteLine($"{(int)response.StatusCode} {root}");
return 1;
}
Console.WriteLine(root.GetProperty("data").GetProperty("dados_pessoais").GetProperty("nome_completo").GetString());
var resized = root.TryGetProperty("imageResized", out var flag) && flag.GetBoolean();
Console.WriteLine($"resized: {resized} credits: {root.GetProperty("creditsCharged")}");
return 0;A URL or the file in base64
"imageType": "url"withimageUrl: a public, direct link to the file that opens without a login. A private or local address is refused withIMAGE_URL_NOT_ALLOWED, and a link that does not download, withIMAGE_DOWNLOAD_FAILED."imageType": "base64"withimageBase64: the file's content in base64, with or without thedata:image/jpeg;base64,prefix.
bash
#!/usr/bin/env bash
# Extract a certificate from a local file, sent in base64. The JSON body is
# written to a file, so a large image never becomes a shell argument.
# Needs DOCSOCR_API_KEY in the environment.
set -euo pipefail
FILE="certificate.jpg"
REQUEST_ID="local-file-$(date +%s)-$RANDOM" # one id per document
{
printf '{"imageType":"base64","requestId":"%s","imageBase64":"' "$REQUEST_ID"
base64 < "$FILE" | tr -d '\n'
printf '"}'
} > body.json
# The API answers within 90 s
curl -sS --max-time 120 https://api.docsocr.com/api/v1/documents/birth-certificate \
-H "Authorization: Bearer $DOCSOCR_API_KEY" \
-H "Content-Type: application/json" \
--data-binary @body.jsonpy
"""Extract a certificate from a local file, sent in base64.
Needs the requests package and DOCSOCR_API_KEY in the environment.
"""
import base64
import os
import uuid
import requests
with open("certificate.jpg", "rb") as file:
image_base64 = base64.b64encode(file.read()).decode("ascii")
response = requests.post(
"https://api.docsocr.com/api/v1/documents/birth-certificate",
headers={"Authorization": f"Bearer {os.environ['DOCSOCR_API_KEY']}"},
json={
"imageType": "base64",
"imageBase64": image_base64,
"requestId": str(uuid.uuid4()), # one id per document
},
timeout=120, # above the API's 90 s extraction budget
)
answer = response.json()
if response.status_code != 201 or not answer["success"]:
raise SystemExit(f"{response.status_code} {answer.get('errorCode', '')} {answer.get('message') or answer.get('error')}")
print(answer["data"]["dados_pessoais"]["nome_completo"])js
// Extract a certificate from a local file, sent in base64.
// Needs Node.js 18+ and DOCSOCR_API_KEY in the environment.
import { randomUUID } from 'node:crypto'
import { readFile } from 'node:fs/promises'
const imageBase64 = (await readFile('certificate.jpg')).toString('base64')
const response = await fetch('https://api.docsocr.com/api/v1/documents/birth-certificate', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.DOCSOCR_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
imageType: 'base64',
imageBase64,
requestId: randomUUID(), // one id per document
}),
signal: AbortSignal.timeout(120_000), // above the API's 90 s extraction budget
})
const answer = await response.json()
if (response.status !== 201 || !answer.success) {
console.error(response.status, answer.errorCode ?? '', answer.message ?? answer.error)
process.exit(1)
}
console.log(answer.data.dados_pessoais.nome_completo)php
<?php
// Extract a certificate from a local file, sent in base64.
// Needs the curl extension and DOCSOCR_API_KEY in the environment.
$imageBase64 = base64_encode(file_get_contents('certificate.jpg'));
$request = curl_init('https://api.docsocr.com/api/v1/documents/birth-certificate');
curl_setopt_array($request, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120, // above the API's 90 s extraction budget
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('DOCSOCR_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'imageType' => 'base64',
'imageBase64' => $imageBase64,
'requestId' => bin2hex(random_bytes(16)), // one id per document
]),
]);
$body = curl_exec($request);
if ($body === false) {
fwrite(STDERR, curl_error($request) . PHP_EOL);
exit(1);
}
$status = curl_getinfo($request, CURLINFO_RESPONSE_CODE);
$answer = json_decode($body, true);
if ($status !== 201 || empty($answer['success'])) {
fwrite(STDERR, "$status " . ($answer['errorCode'] ?? '') . ' ' . implode('; ', (array) ($answer['message'] ?? $answer['error'] ?? '')) . PHP_EOL);
exit(1);
}
echo $answer['data']['dados_pessoais']['nome_completo'], PHP_EOL;java
// Extract a certificate from a local file, sent in base64.
// Needs Java 17+ and DOCSOCR_API_KEY in the environment. Run: java LocalFile.java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Base64;
import java.util.UUID;
public class LocalFile {
public static void main(String[] args) throws Exception {
String imageBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(Path.of("certificate.jpg")));
String body = """
{"imageType": "base64", "requestId": "%s", "imageBase64": "%s"}"""
.formatted(UUID.randomUUID(), imageBase64); // one id per document
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.docsocr.com/api/v1/documents/birth-certificate"))
.timeout(Duration.ofSeconds(120)) // above the API's 90 s extraction budget
.header("Authorization", "Bearer " + System.getenv("DOCSOCR_API_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
// The answer is JSON: read data.dados_pessoais.nome_completo with your JSON library
System.out.println(response.body());
if (response.statusCode() != 201 || !response.body().contains("\"success\":true")) {
System.exit(1);
}
}
}csharp
// Extract a certificate from a local file, sent in base64.
// Needs .NET 8+ and DOCSOCR_API_KEY in the environment. Run: dotnet run LocalFile.cs (.NET 10)
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
var imageBase64 = Convert.ToBase64String(await File.ReadAllBytesAsync("certificate.jpg"));
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(120) }; // above the API's 90 s extraction budget
http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("DOCSOCR_API_KEY"));
var body = new JsonObject
{
["imageType"] = "base64",
["imageBase64"] = imageBase64,
["requestId"] = Guid.NewGuid().ToString(), // one id per document
};
using var content = new StringContent(body.ToJsonString(), Encoding.UTF8, "application/json");
using var response = await http.PostAsync("https://api.docsocr.com/api/v1/documents/birth-certificate", content);
using var answer = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var root = answer.RootElement;
if ((int)response.StatusCode != 201 || !root.GetProperty("success").GetBoolean())
{
Console.Error.WriteLine($"{(int)response.StatusCode} {root}");
return 1;
}
Console.WriteLine(root.GetProperty("data").GetProperty("dados_pessoais").GetProperty("nome_completo").GetString());
return 0;A good photo
- The whole certificate in the frame, edges included, taken straight on.
- Even light, with no glare on the text.
- A sharp image: a blurred photo may come back without data, with
IMAGE_NOT_PROCESSABLE, at no charge.
Each refusal has its errorCode and a message that says what to do: see Errors.