mirror of
https://github.com/GoogleChromeLabs/squoosh.git
synced 2025-11-14 01:37:26 +00:00
# Conflicts: # codecs/cpp.Dockerfile # codecs/imagequant/example.html # codecs/webp/dec/webp_dec.d.ts # codecs/webp/dec/webp_dec.js # codecs/webp/dec/webp_dec.wasm # codecs/webp/enc/webp_enc.d.ts # codecs/webp/enc/webp_enc.js # codecs/webp/enc/webp_enc.wasm # package-lock.json # package.json # src/codecs/tiny.webp # src_old/codecs/encoders.ts # src_old/codecs/processor-worker/tiny.avif # src_old/codecs/processor-worker/tiny.webp # src_old/codecs/tiny.webp # src_old/components/compress/index.tsx # src_old/lib/util.ts # src_old/sw/util.ts
74 lines
1.5 KiB
TypeScript
74 lines
1.5 KiB
TypeScript
import { WorkerResizeOptions } from './processor-meta';
|
|
import { getContainOffsets } from './util';
|
|
import { resize as codecResize } from '../../../codecs/resize/pkg';
|
|
|
|
function crop(
|
|
data: ImageData,
|
|
sx: number,
|
|
sy: number,
|
|
sw: number,
|
|
sh: number,
|
|
): ImageData {
|
|
const inputPixels = new Uint32Array(data.data.buffer);
|
|
|
|
// Copy within the same buffer for speed and memory efficiency.
|
|
for (let y = 0; y < sh; y += 1) {
|
|
const start = (y + sy) * data.width + sx;
|
|
inputPixels.copyWithin(y * sw, start, start + sw);
|
|
}
|
|
|
|
return new ImageData(
|
|
new Uint8ClampedArray(inputPixels.buffer.slice(0, sw * sh * 4)),
|
|
sw,
|
|
sh,
|
|
);
|
|
}
|
|
|
|
/** Resize methods by index */
|
|
const resizeMethods: WorkerResizeOptions['method'][] = [
|
|
'triangle',
|
|
'catrom',
|
|
'mitchell',
|
|
'lanczos3',
|
|
];
|
|
|
|
export async function resize(
|
|
data: ImageData,
|
|
opts: WorkerResizeOptions,
|
|
): Promise<ImageData> {
|
|
let input = data;
|
|
|
|
if (opts.fitMethod === 'contain') {
|
|
const { sx, sy, sw, sh } = getContainOffsets(
|
|
data.width,
|
|
data.height,
|
|
opts.width,
|
|
opts.height,
|
|
);
|
|
input = crop(
|
|
input,
|
|
Math.round(sx),
|
|
Math.round(sy),
|
|
Math.round(sw),
|
|
Math.round(sh),
|
|
);
|
|
}
|
|
|
|
const result = codecResize(
|
|
new Uint8Array(input.data.buffer),
|
|
input.width,
|
|
input.height,
|
|
opts.width,
|
|
opts.height,
|
|
resizeMethods.indexOf(opts.method),
|
|
opts.premultiply,
|
|
opts.linearRGB,
|
|
);
|
|
|
|
return new ImageData(
|
|
new Uint8ClampedArray(result.buffer),
|
|
opts.width,
|
|
opts.height,
|
|
);
|
|
}
|