A photo exceeds an upload limit, and you want to reduce it locally. With browser image compression, JavaScript can decode the file, draw its pixels to a canvas, and encode a new image. The result is a new file, not a smaller copy of the original bytes.
This example explains that pipeline without assuming that every output will be smaller. It is a teaching example, not a benchmark of a browser or compression service. Keep the original until you have checked the downloaded result.
Correction: createImageBitmap() respects EXIF orientation by default. Earlier performance figures are omitted here because this article does not provide the evidence needed to reproduce them.
On this page
- Decode pixels with the correct EXIF orientation
- Understand what canvas re-encoding changes
- Build a JPEG encoder with explicit failure handling
- Keep the download filename and object URL consistent
- Choose quality and format without promising a reduction
- Recognize metadata, color, and memory boundaries
- Check representative outputs before using the workflow
Decode pixels with the correct EXIF orientation#
A JPEG can store orientation instructions separately from its pixel data. That is why using stored dimensions and rotating by guesswork can produce an incorrectly oriented result.
MDN documents the createImageBitmap options: imageOrientation: "from-image" applies EXIF orientation when present and is already the default. Writing it explicitly makes the intended behavior clear; it does not fix a default that ignores EXIF. Use the resulting bitmap dimensions and avoid applying the original orientation a second time.
The function returns a promise, but that alone does not establish a particular thread allocation, decoding speed, or advantage over every alternative. Browser implementation, image dimensions, and available memory affect the workflow. Handle decoding failures instead of assuming that a familiar filename extension guarantees readable image data.
Understand what canvas re-encoding changes#
The canvas contains rendered pixels rather than the original JPEG compression settings. Drawing an image and exporting it asks the browser to encode those pixels again. It is not a byte-preserving edit, and it is not equivalent to removing metadata from the original file.
For ordinary Canvas JPEG output, the quality argument selects a lossy encoding setting. A value of 1 is not an uncompressed or pixel-identical mode. Re-encoding an already compressed JPEG can introduce further differences and can increase its size.
JPEG also cannot preserve transparency. The example deliberately paints a white background before drawing. For a logo or interface asset that needs transparent pixels, choose an alpha-capable format instead; do not silently flatten it and call the result unchanged.
Build a JPEG encoder with explicit failure handling#
Place this markup in a local HTML page. Put both JavaScript blocks below in one <script type="module"> element after the markup. They use browser APIs without an imported compression library.
<label>Choose one image
<input id="source" type="file" accept="image/jpeg,image/png,image/webp">
</label>
<p id="status" role="status"></p>
<a id="download" hidden>Download JPEG</a>
MDN documents toBlob output and failure behavior. Unsupported requested formats fall back to PNG, and the callback can receive null. Checking the returned MIME type prevents a fallback PNG from being offered with a JPEG filename.
async function encodeJpeg(file, quality = 0.8) {
if (!Number.isFinite(quality) || quality < 0 || quality > 1) {
throw new RangeError('Quality must be between 0 and 1.');
}
const bitmap = await createImageBitmap(file, {
imageOrientation: 'from-image'
});
try {
const canvas = document.createElement('canvas');
canvas.width = bitmap.width;
canvas.height = bitmap.height;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas is unavailable.');
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(bitmap, 0, 0);
const blob = await new Promise((resolve, reject) => {
canvas.toBlob(
result => result
? resolve(result)
: reject(new Error('Encoding returned no image.')),
'image/jpeg', quality
);
});
if (blob.type !== 'image/jpeg') {
throw new Error('JPEG output is not supported.');
}
return blob;
} finally {
bitmap.close();
}
}
The white fill is a deliberate conversion decision, not a compression trick. The finally block closes the decoded bitmap after success or failure. A rejected decode never reaches that block because no bitmap was obtained. This example does not add support for formats the browser cannot decode.
Keep the download filename and object URL consistent#
The following handler presents a download link rather than forcing a download. It reports input and output bytes without assuming that the difference is a saving. Disabling the input during processing avoids competing conversions updating the same link.
const input = document.querySelector('#source');
const link = document.querySelector('#download');
const status = document.querySelector('#status');
let outputUrl;
input.addEventListener('change', async () => {
const file = input.files[0];
if (!file) return;
input.disabled = true;
link.hidden = true;
link.removeAttribute('href');
if (outputUrl) URL.revokeObjectURL(outputUrl);
outputUrl = undefined;
status.textContent = 'Encoding...';
try {
const blob = await encodeJpeg(file);
outputUrl = URL.createObjectURL(blob);
link.href = outputUrl;
link.download = file.name.replace(/\.[^.]*$/, '') + '-reencoded.jpg';
link.hidden = false;
status.textContent = file.size + ' bytes to ' + blob.size + ' bytes';
} catch {
status.textContent = 'Could not encode this file.';
} finally {
input.disabled = false;
}
});
The extension is deliberately changed to .jpg because the encoder accepts only JPEG output. Preserving an input .png extension would mislabel the file. The filename suffix also distinguishes the result from the selected original.
An object URL gives the link access to its Blob. Keep that URL available while the reader can use the link; revoke the previous one when replacing it, as above. If an application removes the download interface, it should revoke its remaining URL then. Do not immediately revoke a URL that still backs an available download.
Choose quality and format without promising a reduction#
The example uses 0.8 as a starting setting, not a universal sweet spot. Compare your actual output at the intended display size, then inspect text, edges, and gradients closely. A photo and a screenshot can tolerate very different changes.
Google’s WebP documentation describes lossy and lossless compression, including transparency support. That does not make Canvas WebP quality 1 a guaranteed lossless setting, or make equal JPEG and WebP quality numbers equivalent. Browser decoding support and Canvas encoding support are also separate questions.
Resizing is another decision: fewer pixels may help meet a file-size limit, but the dimensions have changed. This example preserves the decoded dimensions. The image file-size methods guide discusses resizing and format choices; evaluate those trade-offs separately from this encoder’s quality argument.
Recognize metadata, color, and memory boundaries#
The original file’s EXIF and similar metadata are not copied by this pixel-only example. That is narrower than promising a metadata-free output: the browser can write new encoding metadata, and MDN specifies 96 dpi for formats supporting resolution metadata. Orientation handling during decoding is separate from preserving the original orientation tag.
Canvas drawing and export are not an archival workflow for preserving camera metadata, color profiles, bit depth, animation, or exact source pixels. Color handling can affect appearance. Visible information such as text, faces, or a location in the picture remains even when an original GPS tag is absent.
A small compressed file can expand into a large decoded bitmap and canvas. Production applications need dimension and memory limits, cancellation behavior, and testing on their supported browsers. This example does not promise support for arbitrarily large files or consistent speed across devices.
The snippets themselves contain no upload request. That does not establish the behavior of an enclosing website, its analytics, or browser extensions. Local encoding is a useful design choice, not a complete privacy or compliance assessment.
Check representative outputs before using the workflow#
Try an EXIF-oriented portrait, a transparent PNG, and an already compressed JPEG. Reopen each downloaded file: check orientation, dimensions, the intended white background, visual differences, and the reported byte count. Also try an unreadable file and confirm that the interface recovers without leaving an old download link visible.
For repeated directory processing, the QuickShrink CLI and CI guide covers a different pipeline, including output collisions and orientation caveats. Its behavior should not be inferred from these browser APIs.
Keep the original whenever the new file is larger, the visual changes are unacceptable, or metadata preservation matters. Before adding batch processing, decide which formats, dimensions, and failure cases your application will accept, then verify those decisions with representative files.