add image dimension detection for most common formats

This commit is contained in:
dswbx
2025-03-27 09:21:58 +01:00
parent f8f5ef9c98
commit 9407f3d212
10 changed files with 352 additions and 241 deletions

View File

@@ -75,13 +75,20 @@ export class AppMedia extends Module<typeof mediaConfigSchema> {
return this._storage!;
}
uploadedEventDataToMediaPayload(info: FileUploadedEventData) {
uploadedEventDataToMediaPayload(info: FileUploadedEventData): MediaFieldSchema {
const metadata: any = {};
if (info.meta.width && info.meta.height) {
metadata.width = info.meta.width;
metadata.height = info.meta.height;
}
return {
path: info.name,
mime_type: info.meta.type,
size: info.meta.size,
etag: info.etag,
modified_at: new Date(),
metadata,
};
}

View File

@@ -1,8 +1,9 @@
import { type EmitsEvents, EventManager } from "core/events";
import { type TSchema, isFile } from "core/utils";
import { type TSchema, isFile, detectImageDimensions } from "core/utils";
import { isMimeType } from "media/storage/mime-types-tiny";
import * as StorageEvents from "./events";
import type { FileUploadedEventData } from "./events";
import { $console } from "core";
export type FileListObject = {
key: string;
@@ -10,7 +11,7 @@ export type FileListObject = {
size: number;
};
export type FileMeta = { type: string; size: number };
export type FileMeta = { type: string; size: number; width?: number; height?: number };
export type FileBody = ReadableStream | File;
export type FileUploadPayload = {
name: string;
@@ -102,7 +103,7 @@ export class Storage implements EmitsEvents {
}
// try to get better meta info
if (!isMimeType(info?.meta.type, ["application/octet-stream", "application/json"])) {
if (!isMimeType(info.meta.type, ["application/octet-stream", "application/json"])) {
const meta = await this.#adapter.getObjectMeta(name);
if (!meta) {
throw new Error("Failed to get object meta");
@@ -110,6 +111,19 @@ export class Storage implements EmitsEvents {
info.meta = meta;
}
// try to get width/height for images
if (info.meta.type.startsWith("image") && (!info.meta.width || !info.meta.height)) {
try {
const dim = await detectImageDimensions(file as File);
info.meta = {
...info.meta,
...dim,
};
} catch (e) {
$console.warn("Failed to get image dimensions", e);
}
}
const eventData = {
file,
...info,

View File

@@ -7,7 +7,7 @@ import type {
PutObjectRequest,
} from "@aws-sdk/client-s3";
import { AwsClient, isDebug } from "core";
import { type Static, Type, isFile, parse, pickHeaders, pickHeaders2 } from "core/utils";
import { type Static, Type, isFile, parse, pickHeaders2 } from "core/utils";
import { transform } from "lodash-es";
import type { FileBody, FileListObject, StorageAdapter } from "../Storage";
@@ -178,7 +178,6 @@ export class StorageS3Adapter extends AwsClient implements StorageAdapter {
const res = await this.fetch(url, {
method: "GET",
headers: pickHeaders2(headers, [
"range",
"if-none-match",
"accept-encoding",
"accept",