Search code examples
node.jsexpressaxios

How to verify the size of an Image returned through a GET request from OpenLibrary API on Node.js Axios and Express


I have a question. So, I'm making a book library using the Openlibrary API to retrieve data such as book covers in .jpg format. Now the problem I'm encountering some book covers are returned very small at 1px, and I want to handle that issue by replacing the book cover by a local stored "No image Available" image.jpg.

I did some research. I found that I can make head requesst using axios, but I can't seem to get the hang of it.

I tried AI and found this, but it doesn't complete the main goal of verifying if the cover size is < 100px it should return the no image available picture.

// to verify if book image exists 
async function checkImageUrl(isbn) {
    const imageUrl = `https://covers.openlibrary.org/b/isbn/${isbn}-L.jpg`;
    const fallbackImage = 'images/image.png'
    try {
        // Make a HEAD request to check if the image exists
        const response = await axios.head(imageUrl);
        // If the status is 200, the image exists
        return response.status === 200 ? imageUrl : fallbackImage;
    } catch (error) {
        // If there is an error (e.g., 404), return false
        return fallbackImage;
    }
}

Here is what AI returned.
any help is appreciated.


Solution

  • You can use image-pixels package which gives pixel data (width, height) of the image, so you can easily check the required dimension.

    import pixels from 'image-pixels';
    // const pixels = require('image-pixels');  If commonJS
    
    async function checkImageSize(){
    
        const imageUrl = `https://covers.openlibrary.org/b/isbn/${isbn}-L.jpg`;
        const fallbackImage = 'images/image.png';
        const { width , height } = await pixels(imageUrl); // return width,height in PX
        if(width < 100){
            return fallbackImage;
        }
        return imageUrl
        
    }