jquery+html 压缩图片

2023-06-25 23:16:06 浏览数 (1)

代码语言: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

代码语言:javascript复制
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
            // 生成canvas
            const 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) {
        // basic

        url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
        // mozilla(firefox)

        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
        // webkit or chrome

        url = window.webkitURL.createObjectURL(file);
    }

    return url;
}

参考:

https://github.com/kingwsi/compress-pic/blob/master/index.html

0 人点赞