@ankhzet/goo
Version:
Elegoo .goo file format reader/writer
73 lines (72 loc) • 2.21 kB
JavaScript
import sharp from 'sharp';
import { promisify, transformInCoordinateSystem } from './utils.js';
export const loadPreview = async (pathname, { x, y }) => (sharp(pathname, { pages: 1 })
.resize({
width: x,
height: y,
fit: 'contain',
withoutEnlargement: false,
withoutReduction: false,
kernel: 'lanczos3',
})
.raw({
depth: 'uchar',
})
.toBuffer({ resolveWithObject: true })
.then(({ data: buffer, info }) => ({
buffer,
channels: info.channels,
})));
const sliceCanvas = ({ resolution: { x, y } }) => ({
create: {
width: x,
height: y,
channels: 4,
background: '#000000',
},
});
export const loadSlice = async (pathname, transform, printer) => {
const [buffer, info] = await promisify(async (cb) => {
const slice = sharp(pathname);
const { x: left, y: top, width, height } = transformInCoordinateSystem(printer, transform, await slice.metadata());
sharp(sliceCanvas(printer))
.composite([{
input: await (slice
.resize({
width,
height,
fit: 'contain',
withoutEnlargement: false,
withoutReduction: false,
kernel: 'lanczos3',
background: (transform === null || transform === void 0 ? void 0 : transform.invert) ? '#ffffff' : '#000000',
})
.negate((transform === null || transform === void 0 ? void 0 : transform.invert) || false)
.toBuffer()),
left,
top,
}])
.grayscale()
.raw({
depth: 'uchar',
})
.toBuffer(cb);
});
return {
buffer,
channels: info.channels,
};
};
export const saveImage = ({ dimensions, input, pathname }) => {
if (typeof input === 'string') {
return sharp(input).toFile(pathname);
}
return (sharp(input.buffer, {
raw: {
width: dimensions.x,
height: dimensions.y,
channels: input.channels,
},
})
.toFile(pathname));
};