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;
}
}
Created
July 10, 2023 02:52
-
-
Save fuji44/7d253b1806e23b3582287b92eb9c54aa to your computer and use it in GitHub Desktop.
[TypeScript] Checking image URLs using magic numbers
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment