2022-07-01 15:47:48 +00:00
|
|
|
import sizeOf from 'image-size';
|
2022-07-25 21:16:11 +00:00
|
|
|
import fs from 'node:fs/promises';
|
2022-08-30 21:09:44 +00:00
|
|
|
import { fileURLToPath } from 'node:url';
|
2023-03-10 15:19:57 +00:00
|
|
|
import type { InputFormat } from '../loaders/index.js';
|
|
|
|
import type { ImageMetadata } from '../vite-plugin-astro-image.js';
|
2022-07-01 15:47:48 +00:00
|
|
|
|
2022-09-22 19:48:14 +00:00
|
|
|
export interface Metadata extends ImageMetadata {
|
|
|
|
orientation?: number;
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function metadata(src: URL | string, data?: Buffer): Promise<Metadata | undefined> {
|
2022-09-22 19:50:47 +00:00
|
|
|
const file = data || (await fs.readFile(src));
|
2023-06-30 14:38:23 +00:00
|
|
|
const { width, height, type, orientation } = sizeOf(file);
|
2022-07-22 19:14:00 +00:00
|
|
|
const isPortrait = (orientation || 0) >= 5;
|
2022-07-01 15:47:48 +00:00
|
|
|
|
|
|
|
if (!width || !height || !type) {
|
|
|
|
return undefined;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2023-06-30 14:38:23 +00:00
|
|
|
// We shouldn't call fileURLToPath function if it starts with /@astroimage/ because it will throw Invalid URL error
|
|
|
|
src: typeof src === 'string' && /^[\/\\]?@astroimage/.test(src) ? src : fileURLToPath(src),
|
2022-07-22 19:14:00 +00:00
|
|
|
width: isPortrait ? height : width,
|
|
|
|
height: isPortrait ? width : height,
|
2022-07-01 17:43:26 +00:00
|
|
|
format: type as InputFormat,
|
2022-09-22 19:48:14 +00:00
|
|
|
orientation,
|
2022-07-01 17:43:26 +00:00
|
|
|
};
|
2022-07-01 15:47:48 +00:00
|
|
|
}
|