How to get the dimensions of an externally imported image?

Hi! I’m new around here in the forum but have been tweaking a website project of mine in Wix Editor for a while.

I’m trying to externally import multiple images to my Wix Media and then add them to a Media Gallery field in one of my collections.

With the code below I get errors because the uploadResponse doesn’t have width nor height properties (shouldn’t it?), but if I substitute those parts for something like 100, then I successfully import all images and add them to my collection with a 100x100 size. But I still need the original dimensions of the images and I’m seeing no way of getting them…

upload.jsw

import { mediaManager } from 'wix-media-backend';

export async function uploadImageToWix(imageUrl, gameId) {
    try {
        const folderPath = `${gameId}`;
    
        // Import image from external URL
        const uploadResponse = await mediaManager.importFile(
            folderPath,
            imageUrl
        );  
    
        const wixFileUrl = `wix:image://v1/${uploadResponse.fileName}/${uploadResponse.fileName}#originWidth=${uploadResponse.width}&originHeight=${uploadResponse.height}`; // PROBLEM HERE
        return [wixFileUrl, uploadResponse.width, uploadResponse.height]; // PROBLEM HERE
    } catch (error) {
        console.error(`Error uploading image ${imageUrl}:`, error);
        return null;
    }
}

updateGames.jsw

import wixData from 'wix-data';
import { uploadImageToWix } from 'backend/upload';

async function uploadImages(imageUrls, gameId) {
    let wixGalleryImages = [];
    
    for (let i = 0; i < imageUrls.length; i++) {
        const uploadedImage = await uploadImageToWix(imageUrls[i], gameId);
        if (uploadedImage) {
            wixGalleryImages.push(
                {
                    description: "",
                    slug: "",
                    alt: "",
                    src: uploadedImage[0],
                    title: "",
                    type: "image",
                    settings: {
                        "width":uploadedImage[1], // PROBLEM HERE
                        "height":uploadedImage[2], // PROBLEM HERE
                        "focalPoint":[0.5,0.5]
                    }
                }
            );
        }
    }
    
    return wixGalleryImages;
}

Can somebody point me in the right direction? How can I get the original dimensions of the images?

Thank you in advance for any help!

Have you tried mediaManager.getFileInfo()?

You can use the fileUrl or fileName returned from the importFile() response to get the original image dimensions.

I will investigate whether the importFile() response object is meant to return the width and height to clarify the expected behavior.

@thomasj thank you for the reply!

Yes I have tried the getFileInfo() as well but got no results.

Supposedly it should receive a fileUrl, but according to the API, it needs the actual dimensions, so I tried using the deprecated fileName that still seems to work.

However, when printing the width and height to the console I just get null on both.

I checked the whole fileInfo to see its contents, and there were no dimensions there, despite being an image. I wonder what I’m missing here… :thinking:

mediaType: "image"
isPrivate: false
sizeInBytes: 247205
fileName: "afea78_f2e1455902a5429d942556e540273408~mv2.jpg"
originalFileName: "618c2031a07bbff6b4f611f10b6bcdbc.jpg"
mimeType: "image/jpeg"
hash: ""
parentFolderId: "dad38f4d1992400a998b5111bedf08c0"
_createdDate: "2025-03-04T01:42:28.000Z"
_updatedDate: "2025-03-04T01:42:28.000Z"

The dimensions do show in the getFileInfo() API though.

import { Permissions, webMethod } from "wix-web-module";
import { mediaManager } from "wix-media-backend";

export const getFileInfo = webMethod(Permissions.Anyone, async (fileUrl) => {
  return mediaManager.getFileInfo(fileUrl);
});

/* Returns a promise that resolves to:
 * {
 *   "fileUrl": "wix:image://v1/f6c0f9_tg439f4475a749e181dd14407fdbd37e~mv2.jpg/original-name.jpg#originWidth=300&originHeight=300",
 *   "hash": "Ew00kXbu4Zt33rzjcWa6Ng==",
 *   "sizeInBytes": 51085,
 *   "mimeType": "image/jpeg",
 *   "mediaType": "image",
 *   "isPrivate": false,
 *   "iconUrl": "wix:image://v1/f6c0f9_tg439f4475a749e181dd14407fdbd37e~mv2.jpg/original-name.jpg#originWidth=300&originHeight=300",
 *   "parentFolderId": "2bf470f5be194b319cdb2accc3278ff9",
 *   "originalFileName": "original-name.jpg",
 *   "sourceUrl": "https://somedomain.com/img/original-name.jpg",
 *   "width": 300,
 *   "height": 300,
 *   "labels": [
 *     "Blue",
 *     "Butterfly",
 *     "Turquoise"
 *   ],
 *   "opStatus": "READY"
 * }
 */

Please let me know if you find something!

Any ideas on this?

I also tried npm install image-size to get the image dimensions from there but got this error instead…

YarnPNP: Your application tried to access image-size, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.

Required package: image-size
Required by: /user-code/backend/

Require stack:
- /user-code/backend/upload.jsw
- /user-code/backend/updateGames.jsw
- /user-code/stubmodule-that-does-the-require.js
- /cloud-runtime-code/node_modules/scoped-require/index.js
- /cloud-runtime-code/packages/elementory/cloud-runtime/factories.js
- /cloud-runtime-code/packages/elementory/cloud-runtime/create-app.js
- /cloud-runtime-code/packages/elementory/cloud-runtime/cloud-grid-runner.js
YarnPNP: Both resolutions failed at _load!

Still trying to find a workaround with this, but no success up until now…

Wix’s mediaManager.importFile doesn’t return width and height properties. Instead, you can use an image processing library like sharp in a backend web module to fetch the dimensions before uploading. Alternatively, if the images are hosted externally, you can use an API like image-size or retrieve metadata using JavaScript’s Image object before import.

@user5344
Hi, thank you for the reply!

After playing around with image-size, I was somehow able to get the image dimensions from it!

I’ll leave the relevant parts of my code for anyone that might have a similar problem!

upload.jsw

import { mediaManager } from 'wix-media-backend';
import { imageSize } from 'image-size';
import { fetch } from 'wix-fetch';

export async function uploadImageToWix(imageUrl, gameId, gameName) {
    try {
        // Download the image to a buffer
        const response = await fetch(imageUrl);
        const arrayBuffer = await response.buffer();
        const buffer = Buffer.from(arrayBuffer);

        // Get image dimensions
        const dimensions = imageSize(buffer);
        if (!dimensions || !dimensions.width || !dimensions.height) {
            throw new Error("Could not determine image dimensions");
        }

        // Upload to Wix Media
        const folderPath = `${gameId}-${gameName}/`;
        const uploadResponse = await mediaManager.importFile(folderPath, imageUrl);
        const wixFileUrl = `wix:image://v1/${uploadResponse.fileName}/${uploadResponse.fileName}#originWidth=${dimensions.width}&originHeight=${dimensions.height}`;

        return [wixFileUrl, dimensions.width, dimensions.height, uploadResponse.parentFolderId];
    } catch (error) {
        console.error("Error uploading image:", error);
        return null;
    }
}

updateGames.jsw

import wixData from 'wix-data';
import { fetch } from 'wix-fetch';
import { mediaManager } from 'wix-media-backend';
import { uploadImageToWix } from 'backend/upload';

async function uploadImages(imageUrls, gameId, gameName) {
    if (!Array.isArray(imageUrls) || imageUrls.length === 0) {
        console.error(`No valid images for game ${gameId}-${gameName}:`, imageUrls);
        return [];
    }

    let wixGalleryImages = [];
    let parentFolderId = "";

    for (let i = 0; i < imageUrls.length; i++) {
        let imageUrl = imageUrls[i];

        let uploadedImage = await uploadImageToWix(imageUrl, gameId, gameName);
        parentFolderId = uploadedImage[3];
        if (uploadedImage) {
            wixGalleryImages.push(
                {
                    description: "",
                    slug: "",
                    alt: "",
                    src: uploadedImage[0],
                    title: "",
                    type: "image",
                    settings: {
                        "width":uploadedImage[1],
                        "height":uploadedImage[2],
                        "focalPoint":[0.5,0.5]
                    }
                }
            );
        }
    }
    
    return [wixGalleryImages, parentFolderId];
}

Hope it helps anyone!
Cheers!

That’s the good idea! A person can better understand it if already went through this issue!