face-api/src/dom/imageToSquare.ts

28 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-12-19 17:46:41 +01:00
import { env } from '../env/index';
2020-08-18 13:54:53 +02:00
import { createCanvas, createCanvasFromMedia } from './createCanvas';
import { getContext2dOrThrow } from './getContext2dOrThrow';
import { getMediaDimensions } from './getMediaDimensions';
export function imageToSquare(input: HTMLImageElement | HTMLCanvasElement, inputSize: number, centerImage: boolean = false) {
2020-12-23 17:26:55 +01:00
const { Image, Canvas } = env.getEnv();
2020-08-18 13:54:53 +02:00
if (!(input instanceof Image || input instanceof Canvas)) {
2020-12-23 17:26:55 +01:00
throw new Error('imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement');
2020-08-18 13:54:53 +02:00
}
2020-12-23 17:26:55 +01:00
const dims = getMediaDimensions(input);
const scale = inputSize / Math.max(dims.height, dims.width);
const width = scale * dims.width;
const height = scale * dims.height;
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const targetCanvas = createCanvas({ width: inputSize, height: inputSize });
const inputCanvas = input instanceof Canvas ? input : createCanvasFromMedia(input);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
const offset = Math.abs(width - height) / 2;
const dx = centerImage && width < height ? offset : 0;
const dy = centerImage && height < width ? offset : 0;
getContext2dOrThrow(targetCanvas).drawImage(inputCanvas, dx, dy, width, height);
2020-08-18 13:54:53 +02:00
2020-12-23 17:26:55 +01:00
return targetCanvas;
}