export const acceptedTypes = ['image/png', 'image/jpeg', 'image/webp', 'image/gif'] as const;
export const maxBytes = 10 * 1024 * 1024;
export const minSide = 128;
export const outputSide = 512;
export type Crop = { zoom: number; x: number; y: number };
export const fileProblem = (file: File) => {
if (!(acceptedTypes as readonly string[]).includes(file.type)) return 'Use a PNG, JPEG, WebP or GIF image.';
if (file.size > maxBytes) return `That image is ${(file.size / 1024 / 1024).toFixed(1)} MB. Use one under 10 MB.`;
return null;
};
export const loadImage = (file: File) =>
new Promise<HTMLImageElement>((resolve, reject) => {
const url = URL.createObjectURL(file);
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => {
URL.revokeObjectURL(url);
reject(new Error('That file could not be read as an image.'));
};
img.src = url;
});
// The image always covers the square viewport: at zoom 1 its short side fits exactly, and x/y are pixel offsets of its center.
export const coverScale = (img: { naturalWidth: number; naturalHeight: number }, side: number) => side / Math.min(img.naturalWidth, img.naturalHeight);
export const clampCrop = (img: { naturalWidth: number; naturalHeight: number }, side: number, crop: Crop): Crop => {
const scale = coverScale(img, side) * crop.zoom;
const maxX = Math.max(0, (img.naturalWidth * scale - side) / 2);
const maxY = Math.max(0, (img.naturalHeight * scale - side) / 2);
return { zoom: crop.zoom, x: Math.min(maxX, Math.max(-maxX, crop.x)), y: Math.min(maxY, Math.max(-maxY, crop.y)) };
};
export const renderCrop = (img: HTMLImageElement, side: number, crop: Crop) => {
const canvas = document.createElement('canvas');
canvas.width = outputSide;
canvas.height = outputSide;
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('This browser cannot draw images.');
const ratio = outputSide / side;
const scale = coverScale(img, side) * crop.zoom * ratio;
const w = img.naturalWidth * scale;
const h = img.naturalHeight * scale;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, outputSide / 2 - w / 2 + crop.x * ratio, outputSide / 2 - h / 2 + crop.y * ratio, w, h);
return canvas.toDataURL('image/webp', 0.9);
};