When doing ID card recognition in the project, the base64 format encoding of the image needs to be transmitted, but the photos taken by the mobile phone are too large, and converting them to base64 is simply terrible, so I found a solution.
Knowledge points involved<!DOCTYPE html><html lang=en><head> <meta charset=UTF-8> <meta name=viewport content=width=device-width, initial-scale=1.0> <meta http-equiv=X-UA -Compatible content=ie=edge> <title>Document</title></head><body> <input type=file onchange=loadImg(this)> <hr> <div>800×449, 544KB</div> <img src= <hr> <div>400×224, 157KB</div> <canvas></canvas> <script> // Upload image function loadImg(me) { let img = document.querySelector('img'); let cvs = document.querySelector('canvas'); let file = me.files[0]; // Obtain the file object // Only compress the uploaded image if it is larger than 500KB if (file && (file.size / 1024 > 500)) { let reader = new FileReader(); reader.readAsDataURL( file); // Convert to base64 encoding reader.onload = function (e) { let naturalBase64 = e.target.result; // Get base64 Encoding, this is the original image img.src = naturalBase64; img.onload = function () { let ratio = img.naturalWidth / img.naturalHeight; // Get the original image ratio, in order to compress it in equal ratio cvs.width = 400; cvs .height = cvs.width / ratio; let ctx = cvs.getContext('2d'); ctx.drawImage(img, 0, 0, cvs.width, cvs.height); // Draw on canvas // Base64 of the new image after compression let zipBase64 = cvs.toDataURL(); } } } } </script> </body></html>
renderings
About compressed image sizeHere is an out-of-the-box method. baseStr is a complete Base64 encoding, which includes
base64
Code:
function calcBase(baseStr){ var tag = 'base64,'; baseStr = baseStr.substring(baseStr.indexOf(tag)+tag.length); var eqTagIndex = baseStr.indexOf('='); baseStr = eqTagIndex!=- 1?baseStr.substring(0,eqTagIndex):baseStr; var strLen = baseStr.length; var fileSize = strLen - (strLen / 8) * 2; console.log(file size: + (fileSize / 1024).toFixed(1) + 'KB');}
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.