Read meta data of an image file using JavaScript
In this tutorial, we learn about reading the meta of an image file. Metadata refers to relevant data about the image file and its features. We will use a Javascript library called exif-js for reading EXIF metadata from image files.
Reading the metadata of an image file
EXIF stands for Exchangeable Image File, a standard for storing interchange information in digital image files compressed with JPEG.
Here we will create one Html file for using the image tag or we can also file input to get the image fileThe Html file should have the following script in the header to use the exif-js file.
<script src="https://cdn.jsdelivr.net/npm/exif-js"></script>
And we have to define the tag to input the image element and the id.
<img src="image1.jpg" id="img1" />
And then we embed our JavaScript function in the script tag,
window.onload = getExif; function getExif() { var img1 = document.getElementById("img1"); EXIF.getData(img1, function () { var MetaData = EXIF.getAllTags(this); console.log(JSON.stringify(MetaData, null, "\t")); }); }
We have to wait till the image gets loaded before calling the getExif function so that it doesn’t fail.
EXIF.getdata()
has two parameters: one is the image and the second is the call-back function. Here, we use this keyword to access the image with the metadata.
We console log the metadata in JSON Format.
To run the file, we use the live server feature.
Here’s the complete code,
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://cdn.jsdelivr.net/npm/exif-js"></script> <title>Document</title> </head> <body> <img src="image1.jpg" id="img1" /> <br /> </body> <script> window.onload = getExif; function getExif() { var img1 = document.getElementById("img1"); EXIF.getData(img1, function () { var MetaData = EXIF.getAllTags(this); console.log(JSON.stringify(MetaData, null, "\t")); }); } </script> </html>
Output:
You view the result in dev tools:
Leave a Reply