jquery+html 压缩图片
生活随笔
收集整理的這篇文章主要介紹了
jquery+html 压缩图片
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
<html>
<heard><title>壓縮圖片</title><script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"integrity="sha256-4+XzXVhsDmqanXGHaHvgh1gMQKX40OUvDEBTu8JcmNs=" crossorigin="anonymous"></script>
</heard><body><form action="RequestServlet" method="post" enctype="application/x-www-form-urlencoded"><input type="file" name="myfile" id="file_t" /></form><button id="submit">提交數據</button><p style="color: red;"><img id="avatar" src="" alt="" style="width: 150px;"></p></body>
<script src="photo.js"></script></html>
photo.js
var image_upload; $("#submit").click(function(){if(image_upload==null){alert("請選擇您的圖片哦!!!");}alert(image_upload); });// 加載原圖 $("#file_t").on("change", function (e) {let files = e.target.files;var objUrl = getObjectURL(files[0]);console.log("objUrl = " + objUrl);// if (objUrl) {// $("#beforeImg").attr("src", objUrl).show();// }test(); });// 加載壓縮后的圖 function test() {let files = $("#file_t").prop("files");var previewImg = document.querySelector('#afterImg');this.compressImage(files[0],(file) => {image_upload = file;// alert(file);$("#avatar").attr("src", file);},$.noop); }// 壓縮圖片 compressImage = (file, success, error) => {// 圖片小于1M不壓縮if (file.size < Math.pow(1024, 2)) {return success(file);}const name = file.name; //文件名const reader = new FileReader();reader.readAsDataURL(file);reader.onload = (e) => {const src = e.target.result;const img = new Image();img.src = src;img.onload = (e) => {const w = img.width;const h = img.height;const quality = 0.5; // 默認圖片質量為0.92// 生成canvasconst canvas = document.createElement("canvas");const ctx = canvas.getContext("2d");// 創建屬性節點const anw = document.createAttribute("width");anw.nodeValue = w;const anh = document.createAttribute("height");anh.nodeValue = h;canvas.setAttributeNode(anw);canvas.setAttributeNode(anh);// 鋪底色 PNG轉JPEG時透明區域會變黑色ctx.fillStyle = "#fff";ctx.fillRect(0, 0, w, h);ctx.drawImage(img, 0, 0, w, h);// quality值越小,所繪制出的圖像越模糊const base64 = canvas.toDataURL("image/jpeg", quality); // 圖片格式jpeg或webp可以選0-1質量區間success(base64);};img.onerror = (e) => {error(e);};};reader.onerror = (e) => {error(e);}; };//建立一個可存取到該file的url// jquery js 的代碼:不同瀏覽器下的路徑function getObjectURL(file) {var url = null;if (window.createObjectURL != undefined) {// basicurl = window.createObjectURL(file);} else if (window.URL != undefined) {// mozilla(firefox)url = window.URL.createObjectURL(file);} else if (window.webkitURL != undefined) {// webkit or chromeurl = window.webkitURL.createObjectURL(file);}return url; }參考:
https://github.com/kingwsi/compress-pic/blob/master/index.html
總結
以上是生活随笔為你收集整理的jquery+html 压缩图片的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端大纲路线
- 下一篇: 易语言---时间操作