Compress an image to under 200 KB with one API option
Send max_bytes and the image API lowers JPEG quality until the file fits. Measured on a real photo, with the miss case and the width fix.
Add max_bytes to the optimize call and the API lowers the JPEG quality until the output fits. In our test, a 2.5 MB HEIC photo came out at 193,282 bytes for a 200,000 byte limit. When the limit is too small for the full size, the call still returns a file and sets target_not_met. Lower the width, not the quality.
Many upload forms, CMS fields and email gateways have a hard size cap. You know the number, for example 200 KB, and you want the best picture that fits. Guessing a quality value for each photo does not work, because two photos at the same quality can differ a lot in size. max_bytes lets you state the limit and let the service find the quality.
The request
curl https://api.justapi.tech/v1/image/optimize \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 0f4b8d2e-91a7-4c36-b5e0-7a2d6c1e9f58" \
-d '{
"source": { "url": "https://files.example.com/site-photo.heic" },
"options": { "width": 1600, "format": "jpeg", "max_bytes": 200000 }
}'
max_bytes is a positive whole number of bytes. The response has the usual result object with the signed url and the bytes of the output. The stats object holds original_bytes, output_bytes and, only when the limit was missed, target_not_met: true.
How the search works
The service first encodes the image with the quality you sent, or 76 when you sent none. If that output is already at or under max_bytes, it stops. If not, it runs a binary search over quality between 20 and your starting quality. It keeps the highest quality whose output fits. If even quality 20 does not fit, it returns the quality 20 file and sets target_not_met.
Two consequences matter in practice:
max_bytesis a ceiling, not a target. The search only moves quality down, never up. With the default starting quality of 76, a 400,000 byte limit still returns the quality 76 file if that file is smaller. To spend more of a generous budget, raisequality.- The floor is quality 20. The service does not go lower, and it does not change the size of the picture to make it fit. Dimensions come from
widthandheight, and only from those.
What we measured
We ran the image pipeline on one real photo, a HEIC file of 2,504,910 bytes from our test fixtures. Every row sets width: 1600 and format: jpeg, so the output is 1600 × 2133 pixels, unless the row says otherwise.
| Request | Output bytes | target_not_met |
|---|---|---|
No max_bytes (quality 76) |
248,561 | no |
max_bytes: 200000 |
193,282 | no |
max_bytes: 120000 |
116,411 | no |
max_bytes: 60000 |
58,676 | no |
max_bytes: 20000 |
52,869 | yes |
max_bytes: 5000 |
52,869 | yes |
width: 800, max_bytes: 20000 |
19,503 | no |
max_bytes: 400000 |
248,561 | no |
quality: 95, max_bytes: 400000 |
396,692 | no |
Read the table from the top. The service fits every limit down to 60 KB at the full width. At 20 KB the full width cannot fit, and the output stops at 52,869 bytes, which is what quality 20 produces for this photo. The same limit at 800 pixels wide fits with room to spare. The last two rows show the ceiling effect: with the default quality the 400 KB limit changes nothing, and with a starting quality of 95 the search uses almost the whole budget.
We also looked at the files. On this photo, the quality 20 output at full size has blotchy colour patches on the flat wall, and the 800 pixel version at the same 20 KB limit looks cleaner to us. That is a judgement by eye on one picture, so look at your own images before you set a hard floor.
Handle the miss in code
A missed limit is not an error. The call returns 200 and a file, so your code has to read the flag. This client asks for the width you choose, and when the limit is missed it tries once more at half the width. It sends a new idempotency key for the second request, because a different body is a different job.
import { randomUUID } from 'node:crypto';
async function optimize(sourceUrl, options) {
const res = await fetch('https://api.justapi.tech/v1/image/optimize', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.JUSTAPI_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': randomUUID(),
},
body: JSON.stringify({ source: { url: sourceUrl }, options }),
});
const body = await res.json();
if (!res.ok) throw new Error(`${body.error.code}: ${body.error.message}`);
return body;
}
export async function fitUnder(sourceUrl, limit, width = 1600) {
const options = { width, format: 'jpeg', max_bytes: limit };
let body = await optimize(sourceUrl, options);
if (body.stats.target_not_met) {
body = await optimize(sourceUrl, { ...options, width: Math.round(width / 2) });
}
if (body.stats.target_not_met || body.result.bytes > limit) {
throw new Error(`still ${body.result.bytes} bytes, over the ${limit} limit`);
}
return body.result;
}
We ran this client against a local stub that answers like the API does. The stub missed the limit at 1600 pixels and fit it at 800. The client made two requests with two different keys, returned the second result, and made a single request when the first width was already small enough. We did not call the live service for this article, so run it once with a real key and a test photo.
Decide the retry with care. Each request that produces a smaller file is a billed job, and a missed limit is billed like any other result, because the billing rule looks at the size of the output and not at target_not_met. The no-charge rules list what is free. A better habit is to choose the width and the limit together for each use. For example, a thumbnail at 800 pixels and 60 KB, and a detail view at 1600 pixels and 200 KB.
What max_bytes does not cover
- PNG. PNG stores every pixel exactly, so lowering quality gives the search very little to work with. In our test, a PNG output with
max_bytes: 200000came out at 4,239,830 bytes and was flagged as a miss. For photos, ask forjpegorwebp. A WebP output withmax_bytes: 60000fit at 59,620 bytes. - AVIF. The
formatoption acceptsjpeg,webp,pngandauto. AVIF is not available. - Batches. The batch endpoint accepts
max_bytesinoptions, and inper_image_optionsfor a singleref. Its results do not carry thetarget_not_metflag, so compare each result'sbyteswith your limit. The batch guide shows how to read the results. - PDF output. If the images end up in a PDF, keep JPEG baseline and read the photo report guide. The PDF compress call has its own size target,
max_size_mb.
Before you ship
- Pick the limit from the form or system that enforces it, and leave a small margin.
- Set
widthas well asmax_bytes, so the service never has to hit a limit with quality alone. - Raise
qualityif the limit is generous and you want to use it. - Read
stats.target_not_meton every call, and decide what happens on a miss. - Keep the phone's rotation right.
auto_orientstays on by default. The HEIC guide covers it.
Start free at app.justapi.tech. New accounts get 1 USD of credit with no card, which covers many test photos.