Skip to content

Commit

Permalink
fix: add function to get image format from buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
en9inerd committed Feb 13, 2024
1 parent c9af714 commit b0a8c25
Showing 1 changed file with 27 additions and 3 deletions.
30 changes: 27 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ export function formatErrorMessage(err: Error): string {

export function isAsync(fn: CallableFunction): boolean {
return (
fn?.constructor?.name === 'AsyncFunction' ||
Object.prototype.toString.call(fn) === '[object AsyncFunction]' ||
(fn?.constructor?.name === 'AsyncFunction' ||
Object.prototype.toString.call(fn) === '[object AsyncFunction]') ||
fn instanceof Promise ||
(fn !== null && typeof fn === 'object' && typeof (<Promise<unknown>>fn).then === 'function' && typeof (<Promise<unknown>>fn).catch === 'function')
(fn !== null &&
typeof fn === 'object' &&
typeof (fn as Promise<unknown>).then === 'function' &&
typeof (fn as Promise<unknown>).catch === 'function')
);
}

Expand All @@ -38,6 +41,27 @@ export function addS(str: string): string {
}
}

export function getImageFormat(buffer: Buffer): string | undefined {
const signatures = {
jpg: 'ffd8ffe0',
png: '89504e47',
gif: '47494638',
bmp: '424d',
webp: '52494646',
tiff: '49492a00',
};

const signature = buffer.toString('hex', 0, 8).toLowerCase();
for (const [format, sig] of Object.entries(signatures)) {
if (signature.startsWith(sig)) {
return format;
}
}

// Not recognized
return undefined;
}

export function* chunkify<T>(inputList: T[], num: number): Generator<T[]> {
for (let i = 0; i < inputList.length; i += num) {
yield inputList.slice(i, i + num);
Expand Down

0 comments on commit b0a8c25

Please sign in to comment.