Skip to content

Instantly share code, notes, and snippets.

@l1n
Created November 10, 2024 01:29
Show Gist options
  • Save l1n/b505ac9e24f3b0f70945c11c307aeedc to your computer and use it in GitHub Desktop.
Save l1n/b505ac9e24f3b0f70945c11c307aeedc to your computer and use it in GitHub Desktop.
Adds a download as PNG option to images, transcode using canvas.
// ==UserScript==
// @name WebP to PNG Converter
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Adds context menu option to convert and download WebP images as PNG
// @match *://*/*
// @grant GM_registerMenuCommand
// @grant GM_xmlhttpRequest
// @grant GM_openInTab
// @grant GM_notification
// @connect *
// ==/UserScript==
(function() {
'use strict';
let lastRightClickedImage = null;
// Track the last right-clicked WebP image
document.addEventListener('contextmenu', function(e) {
const target = e.target;
if (target.tagName === 'IMG' && target.src.toLowerCase().endsWith('.webp')) {
lastRightClickedImage = target;
} else {
lastRightClickedImage = null;
}
});
// Register the menu command
GM_registerMenuCommand("Save as PNG", async function() {
if (!lastRightClickedImage) {
return;
}
try {
// Fetch the image using GM_xmlhttpRequest to bypass CORS
GM_xmlhttpRequest({
method: 'GET',
url: lastRightClickedImage.src,
responseType: 'blob',
onload: function(response) {
const imgUrl = URL.createObjectURL(response.response);
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
canvas.toBlob(function(blob) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = lastRightClickedImage.src.split('/').pop().replace('.webp', '.png');
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
URL.revokeObjectURL(imgUrl);
GM_notification({
text: "Image successfully converted and downloaded",
title: "WebP to PNG Converter",
timeout: 3000
});
}, 'image/png');
};
img.src = imgUrl;
},
onerror: function(error) {
console.error('Error fetching image:', error);
GM_notification({
text: "Error fetching image: " + error.message,
title: "WebP to PNG Converter",
timeout: 3000
});
}
});
} catch (error) {
console.error('Error converting WebP to PNG:', error);
GM_notification({
text: "Error converting image: " + error.message,
title: "WebP to PNG Converter",
timeout: 3000
});
}
}, "w");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment