1. 程式人生 > >canvas前端壓縮圖片

canvas前端壓縮圖片

參考 read ble element pre dev 轉換 制圖 status

參考網上的用法,下面是利用canvas進行的圖片壓縮

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="
black" name="apple-mobile-web-app-status-bar-style"> <meta content="telephone=no" name="format-detection"> <meta content="email=no" name="format-detection"> <title>slip</title> <style> *{padding: 0;margin: 0;} </style> </head> <body> <div class
="input"> <input type="file" id="file" accept="image/*"> </div> </body> <script type="text/javascript"> var img=new Image(); var reader=new FileReader(); // 選擇的文件對象 var file = null; var eleFlile=document.querySelector(#file); var canvas=document.createElement(
canvas); var context=canvas.getContext(2d); img.onload=function () { //圖片原始大小 var originWidth = this.width; var originHeight = this.height; //限制圖片大小 var maxWidth = 400; var maxHeight = 400; var targetWidth = originWidth, targetHeight = originHeight; if (originHeight > maxHeight || originWidth > maxWidth) { if (originWidth / originHeight > maxWidth / maxHeight) { //更寬 targetWidth = maxWidth; targetHeight = Math.round(maxWidth * (originHeight / originWidth)); } else { //更高 targetHeight = maxHeight; targetWidth = Math.round(targetHeight * (originWidth / originHeight)) } } //圖片縮放 canvas.width = targetWidth; canvas.height = targetHeight; //清除畫布 context.clearRect(0, 0, targetWidth, targetHeight); //圖片壓縮 context.drawImage(img, 0, 0, targetWidth, targetHeight); //轉換上傳toBlob canvas.toBlob(function (blob) { //圖片ajax上傳 var xhr=new XMLHttpRequest(); //文件上傳成功 xhr.onreadystatechange=function () { if(xhr.status==200){ alert("上傳成功") } }; xhr.open("POST","upload.php",true); xhr.send(bolb); } ,file.type || image/png); var newImg = document.createElement("img"), url = URL.createObjectURL(blob); newImg.onload = function () { // no longer need to read the blob so it‘s revoked URL.revokeObjectURL(url); }; newImg.src = url; document.body.appendChild(newImg); // }) //圖片上傳toDataURL var url=canvas.toDataURL(); var newImg = document.createElement("img") newImg.src = url; document.body.appendChild(newImg); } //文件base64化 reader.onload=function (e) { img.src=e.target.result; }; eleFlile.addEventListener("change",function (event) { file=event.target.files[0]; if(file.type.indexOf("image")==0){ reader.readAsDataURL(file); }else { alert("請傳圖片") } }) </script> </html>

canvas前端壓縮圖片