<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Demo</title>
</head>
<body>
<img src="https://www.keycdn.com/img/blog/convert-to-webp-the-successor-of-jpeg-lg.webp" width="100%" />
<script>
function toJpeg (img){
/*
* Create a new XMLHttpRequest to request image to get image Base64
* Repeat requests will occur here, but are cached :)
*/
var xhr = new XMLHttpRequest();
xhr.open("get", img.src, true);
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status == 200) {
// Here get the binary code of the file and read out contents
var blob = this.response;
var oFileReader = new FileReader();
oFileReader.onloadend = function (e) {
// Create a new Image Obj
var newImg = new Image();
// Set crossOrigin Anonymous (That's important, otherwise it will not be read)
newImg.crossOrigin = "Anonymous";
newImg.onload = function() {
// Create a new Canvas
var canvas = document.createElement("canvas");
// Set 2D context
var context = canvas.getContext("2d");
// Set crossOrigin Anonymous (That's important, otherwise it will not be read)
canvas.crossOrigin = "anonymous";
// Set Width/Height
canvas.width = newImg.width;
canvas.height = newImg.height;
// Start
context.drawImage(newImg, 0, 0);
// Get jpeg Base64
img.src = canvas.toDataURL("image/jpeg");
};
// Load Webp Base64
newImg.src = e.target.result;
};
oFileReader.readAsDataURL(blob);
}
};
xhr.send();
}
document.addEventListener('load', ()=>{
// Call conversion function after page loaded
toJpeg(document.querySelector("img"));
});
</script>
</body>
</html>
frontend — Feb 20, 2022
Made with ❤ and at Mars.