Extracting Image Details to Excel with JavaScript

·

2 min read

I got a requirement to fetch image details from azure storage and get the height, width and aspect ratio of a given image and to insert those information in a excel format.

I used below javascript Packages

  • image-size - To get the image information

  • exceljs - To work with excel

const fs = require('fs');
const path = require('path');
const sizeOf = require('image-size');
const ExcelJS = require('exceljs');

// Function to get image properties
function getImageProperties(imagePath) {
  try {
    const dimensions = sizeOf(imagePath);

    const width = dimensions.width;
    const height = dimensions.height;
    const aspectRatio = width / height;

    return {
      fileName: path.basename(imagePath),
      width: `${width}px`,
      height: `${height}px`,
      aspectRatio: aspectRatio.toFixed(2),
    };
  } catch (err) {
    console.error('Error processing image:', err);
    return null;
  }
}

// Local path to the directory containing the images
const directoryPath = '';

// Create a new Excel workbook and worksheet
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Image Properties');

// Add column headers
worksheet.addRow(['File Name', 'Width', 'Height', 'Aspect Ratio']);

// Read the contents of the directory
fs.readdir(directoryPath, (err, files) => {
  if (err) {
    console.error('Error reading directory:', err);
    return;
  }

  // Filter files to only include image files (e.g., .jpg, .jpeg, .png, .gif)
  const imageFiles = files.filter(file => {
    const extension = path.extname(file).toLowerCase();
    return ['.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(extension);
  });

  // Loop through the image files, get properties, and write to the Excel file
  for (const imageFile of imageFiles) {
    const imagePath = path.join(directoryPath, imageFile);
    const imageProperties = getImageProperties(imagePath);

    if (imageProperties) {
      const { fileName, width, height, aspectRatio } = imageProperties;
      worksheet.addRow([fileName, width, height, aspectRatio]);
    }
  }

  // Save the Excel file
  workbook.xlsx.writeFile('image_properties.xlsx')
    .then(() => {
      console.log('Excel file saved successfully');
    })
    .catch(error => {
      console.error('Error saving Excel file:', error);
    });
});