Project Files
src / media / previewPayload.ts
import {
drawthingsLimits,
encodeJpegPreviewFromBuffer,
getDefaultPreviewOptions,
getSize,
} from "../core-bundle.mjs";
export async function shouldUsePreviewPayload(
originalBytes: Uint8Array,
usePreviews: boolean,
): Promise<boolean> {
if (!usePreviews) return false;
const { width, height } = await getSize(Buffer.from(originalBytes));
return width > 0 && height > 0 && width + height > drawthingsLimits.previewMaxSum;
}
export async function previewPayloadBytes(
originalBytes: Uint8Array,
usePreviews: boolean,
): Promise<Uint8Array> {
if (!(await shouldUsePreviewPayload(originalBytes, usePreviews))) return originalBytes;
const { data } = await encodeJpegPreviewFromBuffer(Buffer.from(originalBytes), getDefaultPreviewOptions());
return new Uint8Array(data);
}
export interface GeneratedPreviewPayload {
bytes: Uint8Array;
sourceWidth: number;
sourceHeight: number;
payloadWidth: number;
payloadHeight: number;
}
export async function generatePreviewPayload(
originalBytes: Uint8Array,
): Promise<GeneratedPreviewPayload> {
const { width: sourceWidth, height: sourceHeight } = await getSize(Buffer.from(originalBytes));
const { data, width: payloadWidth, height: payloadHeight } = await encodeJpegPreviewFromBuffer(
Buffer.from(originalBytes),
getDefaultPreviewOptions(),
);
return {
bytes: new Uint8Array(data),
sourceWidth,
sourceHeight,
payloadWidth,
payloadHeight,
};
}