Skip to content

Instantly share code, notes, and snippets.

@lopezezequiel
Last active May 12, 2017 06:18
Show Gist options
  • Save lopezezequiel/239afaf19358c1edf2987b9ace91ef0b to your computer and use it in GitHub Desktop.
Save lopezezequiel/239afaf19358c1edf2987b9ace91ef0b to your computer and use it in GitHub Desktop.
WebP to PNG Cross-Browser Extension
<a style="color: #FFFFFF; background-color: #4dAe51; padding: 5px; border: 1px solid #FFFFFF; font-size: 1rem; font-family: arial, sans-serif; text-decoration:none; " href="javascript: (function(){var images=document.getElementsByTagName('img');images=[].slice.call(images);for(var i=0;i<images.length;i++){var img=images[i];img.crossOrigin='Anonymous';var canvas=document.createElement('canvas');var context=canvas.getContext('2d');canvas.width=img.naturalWidth;canvas.height=img.naturalHeight;context.drawImage(img,0,0);try{img.src=canvas.toDataURL('image/png')}catch(err){canvas.style.width=img.width+'px';canvas.style.height=img.height+'px';img.parentNode.insertBefore(canvas,img);img.parentNode.removeChild(img)}}})()" onclick="event.preventDefault ? event.preventDefault() : (event.returnValue = false); alert('Arrastre el botón a sus marcadores. Cuando este en un sitio que tenga imágenes en formato WebP haga click en el marcador y las imágenes se convertirán en PNG.');">webp2png</a>
(function() {
var images = document.getElementsByTagName('img');
//htmlcollection to array
images = [].slice.call(images);
for(var i=0; i<images.length; i++) {
var img = images[i];
/* Prevent CORS problems but this will only work if server
* response has the following header on it:
* Access-Control-Allow-Origin "*"
*/
img.crossOrigin = 'Anonymous';
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
//actual image size, not css size
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
context.drawImage(img, 0, 0);
try {
//Replaces the current image with the png image
img.src = canvas.toDataURL('image/png');
} catch(err) { //CORS problems
/* resize the canvas using CSS to keep the original
* dimensions(width & height)
*/
canvas.style.width = img.width + 'px';
canvas.style.height = img.height + 'px';
//insert canvas & remove img
img.parentNode.insertBefore(canvas, img);
img.parentNode.removeChild(img);
}
}
})();
(function(){var images=document.getElementsByTagName('img');images=[].slice.call(images);for(var i=0;i<images.length;i++){var img=images[i];img.crossOrigin='Anonymous';var canvas=document.createElement('canvas');var context=canvas.getContext('2d');canvas.width=img.naturalWidth;canvas.height=img.naturalHeight;context.drawImage(img,0,0);try{img.src=canvas.toDataURL('image/png')}catch(err){canvas.style.width=img.width+'px';canvas.style.height=img.height+'px';img.parentNode.insertBefore(canvas,img);img.parentNode.removeChild(img)}}})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment