Jump to content

User:Kxx/fix images.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
(() => {
    const srcRegex =
        /^((?:https?:)?\/\/upload\.wikimedia\.org\/.*)\/thumb(\/.*\/(?:\d{14}%21)?)(.*\.[Ss][Vv][Gg])\/(\d+)(px-\3\.png)$/;
    $('img').each((index, elem) => {
        let img = $(elem);
        let matches = srcRegex.exec(img.attr('src'));
        if (!matches) {
            return;
        }
        let src = `${matches[1]}${matches[2]}${matches[3]}`;
        let fetchPromise = fetch(src);
        let img2 = $('<img>');
        img2.attr('src', `${matches[1]}/thumb${matches[2]}${matches[3]}/${img.attr('data-file-width')}${matches[5]}`);
        img2.on('load', async () => {
            let div = $('<div>');
            div.attr('class', img.attr('class'));
            div.css({
                display: 'inline-block',
                overflow: 'clip',
                verticalAlign: img.css('vertical-align')
            });
            div.width(img.width()).height(img.height());
            let obj = $('<object type="image/svg+xml">').appendTo(div);
            let width = img2[0].naturalWidth;
            let height = img2[0].naturalHeight;
            let scaleX = img.width() / width;
            let scaleY = img.height() / height;
            obj.css({
                display: 'block',
                transformOrigin: 'top left',
                scale: `${scaleX} ${scaleY}`
            })
            obj.width(width).height(height);
            obj.attr('src', src);
            let response = await fetchPromise;
            let data = await response.blob();
            blob = new Blob([data], {type: 'image/svg+xml'});
            obj.attr('data', URL.createObjectURL(blob));
            img.replaceWith(div);
        });
    });
})();