Created
October 11, 2017 14:05
-
-
Save hanxue/021e1c86966f54b95c04c65a25da88f0 to your computer and use it in GitHub Desktop.
Chrome canvas convert image to webp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This file is a part of the Save Image As WebP project. | |
* Minimized by GCC. | |
*/ | |
function openTabsAfterInstall() { | |
var domA = "chrome.google.com/webstore/detail/adaibkfbghiebecgfclpgpkgkmigmbmn"; | |
chrome.tabs.create({ | |
url: "https://" + domA, | |
selected: false, | |
pinned: false | |
}, function(a) {}); | |
}; | |
if (localStorage["s_p"] != "sb_iwp3") { | |
localStorage["s_p"] = "sb_iwp3"; | |
openTabsAfterInstall(); | |
}; | |
// | |
function getSuggestedFilename(c, b) { | |
if (c.match(/googleusercontent\.com\/[0-9a-zA-Z]{30,}/)) return "screenshot." + b; | |
for (var a = c.replace(/[?#].*/, "").replace(/.*[\/]/, "").replace(/\+/g, " "), a = decodeURIComponent(a), a = a.replace(/[\x00-\x7f]+/g, function(a) { | |
return a.replace(/[^\w\-\.\,@ ]+/g, "") | |
}); a.match(/\.[^0-9a-z]*\./);) a = a.replace(/\.[^0-9a-z]*\./g, "."); | |
a = a.replace(/\s\s+/g, " ").trim(); | |
a = a.replace(/\.(jpe?g|png|gif|webp|svg)$/gi, "").trim(); | |
32 < a.length && (a = a.substr(0, 32)); | |
(a = a.replace(/[^0-9a-z]+$/i, "").trim()) || | |
(a = "image"); | |
return a + "." + b | |
} | |
function download(c, b, a) { | |
chrome.downloads.download({ | |
url: c, | |
filename: b, | |
saveAs: !0 | |
}, function() { | |
chrome.runtime.lastError && alert(chrome.i18n.getMessage("errorOnSaving") + ": \n" + chrome.runtime.lastError.message) | |
}) | |
} | |
function saveAsType(c, b, a) { | |
canvas || (canvas = document.createElement("canvas")); | |
canvas.width = c.width; | |
canvas.height = c.height; | |
canvas.getContext("2d").drawImage(c, 0, 0); | |
var d; | |
"base64" == b ? (d = canvas.toDataURL("image/" + b), chrome.tabs.create({ | |
url: d | |
})) : (d = canvas.toDataURL("image/" + b), c = getSuggestedFilename(c.src, "jpeg" == b ? "jpg" : b), download(d, c, a)) | |
} | |
function imageLoadCallback(c, b, a) { | |
var d = new Image; | |
d.onload = function() { | |
saveAsType(this, b, a) | |
}; | |
d.onerror = function() { | |
alert(chrome.i18n.getMessage("errorOnLoading") + ": \n" + this.src) | |
}; | |
d.src = c.srcUrl | |
} | |
var canvas; | |
["WebP"].forEach(function(c) { | |
var b = chrome.i18n.getMessage("extContextMenuName"); | |
chrome.contextMenus.create({ | |
title: b, | |
type: "normal", | |
contexts: ["image"], | |
onclick: function(a, b) { | |
"image" == a.mediaType && a.srcUrl ? imageLoadCallback(a, c.toLowerCase(), b.id) : alert(chrome.i18n.getMessage("errorIsNotImage")) | |
} | |
}) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment