Image Helper
v1.0.0Browser utilities for validating, loading, resizing, and compressing images.
hasAllowedMimeType
import { ImageHelper } from '@oardi/ts-utils';
const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/webp'] as const;
ImageHelper.hasAllowedMimeType(file, allowedMimeTypes);
The comparison is case-insensitive and ignores surrounding whitespace in whitelist entries. An empty MIME type is rejected. MIME metadata can be missing or misleading, so successful browser decoding remains the authoritative image-content check.
Load an image file
ImageHelper.load() creates an HTMLImageElement from a browser File. The temporary object URL
is revoked automatically after the image has loaded or failed to load.
const image = await ImageHelper.load(file);
Compress an image data URL
compress() draws the image at its intrinsic naturalWidth and naturalHeight and returns a new
data URL. CSS-rendered dimensions do not affect the output. It uses JPEG with a quality of 0.8 by
default.
const compressed = await ImageHelper.compress(imageDataUrl);
const webp = await ImageHelper.compress(imageDataUrl, 0.6, 'image/webp');
Pass a data URL that the browser can load. The requested output type and quality are forwarded to
HTMLCanvasElement.toDataURL().
Resize an image
resize() scales an HTMLImageElement from its intrinsic naturalWidth and naturalHeight down to
fit within the requested dimensions while preserving its aspect ratio. CSS-rendered dimensions are
ignored and images are never enlarged.
const { canvas, width, height } = ImageHelper.resize(image, 1200, 800);
The returned dimensions match the generated canvas. Intrinsic and target dimensions must be finite
and at least 1 pixel; invalid dimensions throw a RangeError. If the browser cannot create a 2D
canvas context, resize() throws an explicit Error instead of failing on a null context.
Browser requirements
hasAllowedMimeType() only requires Blob support. load(), compress(), and resize() require
browser image, canvas, document, or object URL APIs and must not be called during server-side
rendering.
Previous:Helpers
← File HelperNext:Helpers
LocalStorage Helper →