Please bookmark this page to avoid losing your image tool!

Image File Name Translator

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
You can edit the below JavaScript code to customize the image tool.
/**
 * Translates the file name of an image using a public online translation service.
 * The function extracts the file name from the image source URL, translates it to a specified language,
 * and returns an HTML element displaying the original and translated names.
 * Note: This function relies on an external, undocumented API that may change, become unavailable,
 * or have restrictions (e.g., CORS).
 *
 * @param {Image} originalImg The original image object. The file name is extracted from its `src` property.
 * @param {string} [targetLang='en'] The ISO 639-1 code for the target language (e.g., 'es', 'fr', 'ru').
 * @param {string} [sourceLang='auto'] The ISO 639-1 code for the source language. 'auto' attempts to auto-detect.
 * @returns {Promise<HTMLDivElement>} A promise that resolves to a div element containing the translation result.
 */
async function processImage(originalImg, targetLang = 'en', sourceLang = 'auto') {
    const outputContainer = document.createElement('div');
    outputContainer.style.fontFamily = 'Arial, sans-serif';
    outputContainer.style.padding = '20px';
    outputContainer.style.border = '1px solid #ccc';
    outputContainer.style.borderRadius = '8px';
    outputContainer.style.maxWidth = '500px';
    outputContainer.style.margin = '20px auto';
    outputContainer.style.textAlign = 'center';
    outputContainer.style.wordBreak = 'break-word';
    outputContainer.style.backgroundColor = '#f9f9f9';

    const createHeader = (text) => {
        const header = document.createElement('h3');
        header.textContent = text;
        header.style.marginTop = '0';
        header.style.marginBottom = '10px';
        header.style.color = '#333';
        return header;
    };

    const createParagraph = (text) => {
        const p = document.createElement('p');
        p.textContent = text;
        p.style.margin = '0 0 20px 0';
        p.style.fontSize = '1.1em';
        return p;
    };

    const url = originalImg.src;

    // Handle data/blob URLs which do not have a standard, translatable file name in their src.
    if (url.startsWith('data:') || url.startsWith('blob:')) {
        outputContainer.appendChild(createHeader('Error'));
        const p = createParagraph('Cannot extract a file name from a generated image source (data: or blob: URL). Please use an image with a standard path-based URL.');
        p.style.color = '#d9534f';
        outputContainer.appendChild(p);
        return outputContainer;
    }

    // 1. Extract the file name from the URL.
    // Get the part after the last '/' and before any '?', then decode it.
    const fileNameWithExt = decodeURIComponent(url.substring(url.lastIndexOf('/') + 1).split('?')[0]);

    if (!fileNameWithExt) {
        outputContainer.appendChild(createHeader('Error'));
        const p = createParagraph('Could not find a valid file name in the image source URL.');
        p.style.color = '#d9534f';
        outputContainer.appendChild(p);
        return outputContainer;
    }

    // Separate the name from the extension.
    const lastDotIndex = fileNameWithExt.lastIndexOf('.');
    let nameToTranslate, fileExtension;
    // Check if a dot exists and it's not the first character.
    if (lastDotIndex > 0) {
        nameToTranslate = fileNameWithExt.substring(0, lastDotIndex);
        fileExtension = fileNameWithExt.substring(lastDotIndex);
    } else {
        nameToTranslate = fileNameWithExt;
        fileExtension = '';
    }

    // Prepare text for translation (replace common file name separators with spaces).
    const textToTranslate = nameToTranslate.replace(/[-_.]/g, ' ');

    outputContainer.appendChild(createHeader('Original File Name'));
    outputContainer.appendChild(createParagraph(fileNameWithExt));

    // 2. Translate the name using the free Google Translate API.
    try {
        const apiUrl = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&q=${encodeURIComponent(textToTranslate)}`;
        const response = await fetch(apiUrl);
        if (!response.ok) {
            throw new Error(`Network response was not ok: ${response.statusText}`);
        }
        const data = await response.json();

        // The translated text is nested in the response array. We map over the segments and join them.
        const translatedText = data[0].map(item => item[0]).join('');

        // 3. Construct the new file name.
        // Sanitize translated text to be file-system friendly while preserving international characters.
        const sanitizedTranslatedName = translatedText
            .trim()
            .replace(/\s+/g, '_') // Replace spaces with underscores
            .replace(/[\\/:*?"<>|]/g, ''); // Remove characters invalid in file names

        const newFileName = sanitizedTranslatedName + fileExtension;

        outputContainer.appendChild(createHeader(`Translated File Name (to ${targetLang})`));
        const translatedP = createParagraph(newFileName);
        translatedP.style.fontWeight = 'bold';
        translatedP.style.color = '#007bff';
        outputContainer.appendChild(translatedP);

    } catch (error) {
        console.error("Translation failed:", error);
        outputContainer.appendChild(createHeader('Translation Failed'));
        const errorP = createParagraph('Could not translate the file name. The translation service may be unavailable or blocking requests from this origin.');
        errorP.style.color = '#d9534f';
        outputContainer.appendChild(errorP);
    }

    return outputContainer;
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

The Image File Name Translator is a tool designed to translate image file names into different languages. By extracting the file name from an image’s source URL, the tool can translate it to the specified target language using an online translation service. This can be particularly useful for users looking to rename image files in a language other than their original, aiding in file organization and accessibility. Common use cases include preparing images for international audiences, improving multimedia projects, and enhancing file management systems where multilingual support is needed.

Leave a Reply

Your email address will not be published. Required fields are marked *