You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.3 KiB
TypeScript

/**
*
* @param {string} filename
* @returns {boolean}
*/
const IMAGE_EXTENSIONS = new Set([
"jpg",
"jpeg",
"png",
"gif",
"bmp",
"svg",
"webp",
"tiff",
"psd",
"ico",
"jfif",
"apng",
"avif",
]);
export function isImage(filename) {
// 1. 去除路径,只保留文件名
const baseName = filename.split("/").pop().split("\\").pop();
if (!baseName) return false;
// 2. 提取扩展名(处理多扩展名,取最后一个)
const ext = baseName.split(".").pop()?.toLowerCase();
if (!ext || ext.length < 2) return false; // 扩展名长度至少2位如.jpg
// 3. 检查是否在图片扩展名白名单
return IMAGE_EXTENSIONS.has(ext);
}
// 示例测试
// console.log(isImage('photo.jpg')); // true
// console.log(isImage('image.png')); // true
// console.log(isImage('logo.svg')); // true
// console.log(isImage('cover.tar.gz')); // false非图片扩展名
// console.log(isImage('file')); // false无扩展名
// console.log(isImage('.hidden.png')); // true隐藏文件
// console.log(isImage('icon.JPEG')); // true大小写不敏感
// console.log(isImage('video.mp4')); // false视频