我正在尝试使用 JavaScript 确定图像的文件类型,但我尝试的代码将文件类型显示为“jpg”。但是,当我将同一文件传递给外部工具(如 https://exifinfo.org/detail/RjmJqqj8LGEaqOLBEaiyiw)时,它会将文件类型显示为“webp”,这是正确的文件类型。 这是代码:
<!DOCTYPE html>
<html>
<head>
<title>Identify Image File Type</title>
</head>
<body>
<img id="image" src="https://s.alicdn.com/@sc04/kf/H7c1b38f112d044889f7b2c5a2ab914ac3.jpg_100x100xz.jpg">
<script>
const image = document.getElementById('image');
image.addEventListener('load', () => {
const width = image.naturalWidth;
const height = image.naturalHeight;
const url = new URL(image.src);
const extension = url.pathname.split('.').pop();
console.log(`The file type is ${extension}`);
});
image.addEventListener('error', () => {
console.log('The file is not a valid image');
});
</script>
</body>
</html>
我尝试使用第三方库“文件类型”来确定正确的文件类型。这是我试过的代码:
<!DOCTYPE html>
<html>
<head>
<title>Identify Image File Type</title>
</head>
<body>
<img id="image">
<script src="https://cdn.jsdelivr.net/npm/file-type/dist/index.umd.js"></script>
<script>
const imageUrl = 'https://s.alicdn.com/@sc04/kf/H7c1b38f112d044889f7b2c5a2ab914ac3.jpg_100x100xz.jpg';
fetch(imageUrl)
.then(response => response.arrayBuffer())
.then(buffer => {
const fileType = window.fileType.fromBuffer(new Uint8Array(buffer));
const image = document.getElementById('image');
image.addEventListener('load', () => {
const width = image.naturalWidth;
const height = image.naturalHeight;
console.log(`The file type is ${fileType.ext}`);
});
image.addEventListener('error', () => {
console.log('The file is not a valid image');
});
const objectUrl = window.URL.createObjectURL(new Blob([buffer], { type: fileType.mime }));
image.src = objectUrl;
})
.catch(error => {
console.log(`Error fetching image: ${error.message}`);
});
</script>
</body
但它给出了错误: 获取 https://cdn.jsdelivr.net/npm/file-type/dist/index.umd.js net::ERR_ABORTED 404 获取图像时出错:无法读取未定义的属性(读取“fromBuffer”)
有人可以指导我如何在 JavaScript 中正确确定图像的文件类型吗?所讨论图像的理想输出应该是 'webp'。”