Home >Web Front-end >H5 Tutorial >How to compress images with Canvas

How to compress images with Canvas

php中世界最好的语言
php中世界最好的语言Original
2018-01-11 09:37:252146browse

This time I will show you how to use Canvas to compress images? What are the precautions when using Canvas to compress images? The following is a practical case, let’s take a look.

1. Local image input

1. Get local files

<!--HTML-->
<input type="file" id="choose-img" />
// JS
var chooseImg = document.getElementById("choose-img");
chooseImg.onchange = function(e){
    var file = this.files[0];
    // ……  (省略部分代码后续依次展示,下同)
};


It’s very simple, just use the button with type file Get local files.

2. Determine the type of local file obtained

<!--HTML-->
<div id="result"></div>
// JS
var result = document.getElementById("result");    // 用于显示图片输出结果,或者错误提示
if(/image/.test(file.type)){     // 判断文件类型是否为图片
    // ……
}
else{
    result.innerHTML = &#39;<span style="color: red;">文件类型有误!</span>&#39;;
}


3. Output the obtained local image in base64 format

var img = new Image(),      // 创建图片对象,用于放置原始图片
    reader = new FileReader();
reader.readAsDataURL(file);    // 以base64格式读取并存入FileReader对象的result属性中
reader.onload = function(){
    img.src = this.result;   // 将图片base64字符串直接赋予Image对象的src中
    document.body.insertBefore(img,chooseImg);   // 将输出的图片插入到文件按钮之前
    img.onload = function(){
        // ……
    };
};

2. Draw pictures in Canvas

1. Create canvas

var canvas = document.createElement(&#39;canvas&#39;);
canvas.width = img.clientWidth;
canvas.height = img.clientHeight;
var context = canvas.getContext(&#39;2d&#39;);

Note: The size of the canvas is the same as the width and height of the entered picture.

2. Draw pictures

context.drawImage(img,0,0,canvas.width,canvas.height);

3. Compress pictures and output

<!--HTML-->
图片压缩比率 : <input id="rate" type="number" min="0" max="100" /> %
// JS
var chooseImg = document.getElementById("choose-img"),
    result = document.getElementById("result");
chooseImg.onchange = function(e){
    var file = this.files[0];
    if(/image/.test(file.type)){
        var img = new Image(),
            reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(){
            img.src = this.result;
            document.body.insertBefore(img,chooseImg);
            img.onload = function(){
                var canvas = document.createElement(&#39;canvas&#39;);
                canvas.width = img.clientWidth;
                canvas.height = img.clientHeight;
                var context = canvas.getContext(&#39;2d&#39;);
                context.drawImage(img,0,0,canvas.width,canvas.height);
                var rate = document.getElementById("rate").value || 100;
                var imgUrl = canvas.toDataURL(file.type,rate/100);
                result.innerHTML = &#39;压缩后:<img src="&#39;+ imgUrl +&#39;" />&#39;;
                result.style.display = &#39;block&#39;;
                img.style.display = &#39;none&#39;;
            };
        };
    }
    else{
        result.innerHTML = &#39;<span style="color: red;">文件类型有误!</span>&#39;;
    }
};

After testing, it was found that compressing JPEG format pictures through Canvas has the best effect, while the PNG compression effect is not obvious. Sometimes it gets bigger instead.

I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

H5’s block-level tag summary

H5’s advanced inline tag

How to use H5 to call the camera

The above is the detailed content of How to compress images with Canvas. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to wake up h5 appNext article:How to wake up h5 app