Skip to content

Instantly share code, notes, and snippets.

@fuji44
Created July 10, 2023 02:52
Show Gist options
  • Save fuji44/7d253b1806e23b3582287b92eb9c54aa to your computer and use it in GitHub Desktop.
Save fuji44/7d253b1806e23b3582287b92eb9c54aa to your computer and use it in GitHub Desktop.
[TypeScript] Checking image URLs using magic numbers

[TypeScript] Checking image URLs using magic numbers

import axios from "axios";

class ImageUtil {
  public static async isValidImageUrl(url: string) {
    try {
      const response = await axios.get<string>(url, {
        responseType: "arraybuffer",
      });
      const buffer = Buffer.from(response.data, "binary");
      return this.isImageBuffer(buffer);
    } catch (error) {
      logger.error(
        `Exception thrown in image URL checking process. url: ${url}`,
        error
      );
      return false;
    }
  }

  private static isImageBuffer(buffer: Buffer): boolean {
    // Add as needed
    const imageMagicNumbers = [
      { signature: [0xff, 0xd8], kind: "generic-jpeg" },
    ];
    const magicNumber = Array.from(buffer.slice(0, 2));
    const matchedSignature = imageMagicNumbers.find((image) =>
      image.signature.every((byte, index) => byte === magicNumber[index])
    );
    return !!matchedSignature;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment