From e3b053db1292dd77d6866778a04203bc6533eb63 Mon Sep 17 00:00:00 2001 From: Jason Miller Date: Wed, 9 Dec 2020 11:22:43 -0500 Subject: [PATCH] Fix crop preprocessor --- .../preprocessors/crop/worker/crop.ts | 54 +++++-------------- 1 file changed, 14 insertions(+), 40 deletions(-) diff --git a/src/features/preprocessors/crop/worker/crop.ts b/src/features/preprocessors/crop/worker/crop.ts index 2d65c466..b63e6008 100644 --- a/src/features/preprocessors/crop/worker/crop.ts +++ b/src/features/preprocessors/crop/worker/crop.ts @@ -13,51 +13,25 @@ import { Options } from '../shared/meta'; export default async function crop( - data: ImageData, - opts: Options, + { data, width, height }: ImageData, + { top, right, bottom, left }: Options, ): Promise { - const { left, top, right, bottom } = opts; - const source = data.data; - const { width, height } = data; - const cols = width * 4; - const newWidth = width - left - right; const newHeight = height - top - bottom; - const len = newWidth * newHeight * 4; - const pixels = new Uint8ClampedArray(len); + const cols = width * 4; + const newCols = newWidth * 4; + + const pixels = new Uint8ClampedArray(data.buffer, 0, newHeight * newCols); for (let y = 0; y < newHeight; y++) { - for (let x = 0; x < newWidth; x++) { - let i = y * cols + x * 4; - let j = (top + y) * cols + (left + x) * 4; - pixels[i] = source[j]; - pixels[i + 1] = source[j + 1]; - pixels[i + 2] = source[j + 2]; - pixels[i + 3] = source[j + 3]; - } + const x = left * 4; + const row = new Uint8ClampedArray( + data.buffer, + (top + y) * cols + x, + newCols, + ); + pixels.set(row, y * newCols); } - // let sourceX = left; - // let sourceY = top; - // let x = 0; - // let y = 0; - // let i = 0; - // while (i < len) { - // let from = sourceY * cols + sourceX * 4; - - // pixels[i++] = source[from++]; - // pixels[i++] = source[from++]; - // pixels[i++] = source[from++]; - // pixels[i++] = source[from]; - - // if (++x === newWidth) { - // x = 0; - // y++; - - // sourceX = left; - // sourceY++; - // } - // } - - return new ImageData(pixels, newWidth, newHeight); + return new ImageData(pixels.slice(), newWidth, newHeight); }