Skip to content
This repository has been archived by the owner on Jul 19, 2024. It is now read-only.

Commit

Permalink
Added a safeguard for too small images (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nawias authored Mar 29, 2024
1 parent 69b6dbf commit e042537
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/services/converters/ImageMediaConverter.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import MediaConverter, { MediaFile } from "./MediaConverter";

const MAX_IMAGE_DIM = 1024;

type ImageErrorReason = "invalid" | "too large";
const MIN_IMAGE_DIM = 3;
type ImageSizeErrorReason = "too large" | "too small";
type ImageErrorReason = "invalid" | ImageSizeErrorReason;

class ImageError extends Error {
public readonly reason: ImageErrorReason;
Expand All @@ -14,19 +15,26 @@ class ImageError extends Error {
}
}

type ImageCheckResult = "ok" | ImageSizeErrorReason;
export default class ImageMediaConverter extends MediaConverter {
async checkImage(file: Blob): Promise<boolean> {
async checkImage(file: Blob): Promise<ImageCheckResult> {
const image = await createImageBitmap(file);
return image.width <= MAX_IMAGE_DIM && image.height <= MAX_IMAGE_DIM;
if (image.width > MAX_IMAGE_DIM || image.height > MAX_IMAGE_DIM)
return "too large";

if (image.width < MIN_IMAGE_DIM || image.height < MIN_IMAGE_DIM)
return "too small";

return "ok";
}

async convert(files: MediaFile[]): Promise<MediaFile[]> {
const body = new FormData();

for (const file of files) {
try {
if (!(await this.checkImage(file.data)))
throw new ImageError("too large");
const checkResult = await this.checkImage(file.data);
if (checkResult !== "ok") throw new ImageError(checkResult);

body.append(file.filepath, file.data);
} catch (error) {
Expand Down

0 comments on commit e042537

Please sign in to comment.