Home > Web Front-end > H5 Tutorial > body text

Share example code for image compression and upload using HTML5

零下一度
Release: 2017-05-08 13:47:04
Original
2548 people have browsed it
Implementation process:
  • Get the uploaded file by ;

  • Use FileReader to read the image , and create a new Image object to put the image data read by FileReader;

  • Use canvas to scale the Image object proportionally and write it to the canvas, and save it as data in base64 format ( The FormData object upload is used here. In fact, the base64 data can be uploaded directly to the server through ajax using the post method, which can avoid the following two steps);

  • Create a new Blob The object puts base64 data into it;

  • Use the FormData object to upload to a third-party cloud storage server;

Use HTML native Upload images, here are some pitfalls:
  • accept sets the type of uploaded file. Here, use image/* directly without specifying a specific suffix name. Otherwise, some Android phones cannot upload pictures;

  • Add the multiple attribute to select multiple pictures (this example only selects a single picture);

  • capture="camera" attribute can call the camera (adding this attribute will directly call the camera on the iPhone without reading the photo album; and currently Android and ios devices use accept="image/*" You can choose to use the camera to take pictures or use pictures from the album, so this attribute can be ignored).

<input id="imgUpload" type="file" onchange="addPic" accept="image/*" />
Copy after login
Get the uploaded file when the input file triggers the change event
function addPic(e){
  if (typeof FileReader === &#39;undefined&#39;) {
    return alert(&#39;你的浏览器不支持上传图片哟!&#39;);
  }
  var files = e.target.files || e.dataTransfer.files;
  if(files.length > 0){
    imgResize(file[0], callback);
  }
}
Copy after login
Use FileReader to get the image data and use canvas to compress it
  • The ios mobile phone will rotate 90 degrees when taking pictures. It must be judged whether the ios mobile phone handles it accordingly before uploading.

function imgResize(file, callback){
  var fileReader = new FileReader();
  fileReader.onload = function(){
    var IMG = new Image();
    IMG.src = this.result;
    IMG.onload = function(){
      var w = this.naturalWidth, h = this.naturalHeight, resizeW = 0, resizeH = 0;
      // maxSize 是压缩的设置,设置图片的最大宽度和最大高度,等比缩放,level是报错的质量,数值越小质量越低
      var maxSize = {
        width: 500,
        height: 500,
        level: 0.6
      };
      if(w > maxSize.width || h > maxSize.height){
        var multiple = Math.max(w / maxSize.width, h / maxSize.height);
        resizeW = w / multiple;
        resizeH = w / multiple;
      } else {
        // 如果图片尺寸小于最大限制,则不压缩直接上传
        return callback(file)
      }
      var canvas = document.createElement(&#39;canvas&#39;),
      ctx = canvas.getContext(&#39;2d&#39;);
      if(window.navigator.userAgent.indexOf(&#39;iPhone&#39;) > 0){
        canvas.width = resizeH;
        canvas.height = resizeW;
        ctx.rorate(90 * Math.PI / 180);
        ctx.drawImage(IMG, 0, -resizeH, resizeW, resizeH);
      }else{
        canvas.width = resizeW;
        canvas.height = resizeH;
        ctx.drawImage(IMG, 0, 0, resizeW, resizeH);
      }
      var base64 = canvas.toDataURL(&#39;image/jpeg&#39;, maxSize.level);
      convertBlob(window.atob(base64.split(&#39;,&#39;)[1]), callback);
    }
  };
  fileReader.readAsDataURL(file);
}
Copy after login
Convert the base64 data into a Blob object
  • Android phones do not support BlobConstruction method

  • ##
    function convertBlob(base64, callback){
      var buffer = new ArrayBuffer(base64.length);
      var ubuffer = new Uint8Array(buffer);
      for (var i = 0; i < base64.length; i++) {
        ubuffer[i] = base64.charCodeAt(i)
      }
      var blob;
      try {
        blob = new Blob([buffer], {type: &#39;image/jpg&#39;});
      } catch (e) {
        window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
        if(e.name === &#39;TypeError&#39; && window.BlobBuilder){
          var blobBuilder = new BlobBuilder();
          blobBuilder.append(buffer);
          blob = blobBuilder.getBlob(&#39;image/jpg&#39;);
        }
      }
      callback(blob)
    }
    Copy after login
Use
HTML5's FormData Object upload data
function callback(fileResize){
  var data = new FormData();
  data.append(&#39;file&#39;, fileResize);
  var config = {
    headers: {&#39;Content-Types&#39;: &#39;multipart/form-data&#39;}
  };
  // 这里用的es6语法发起请求,可以无视
  axios.post(url, data, config).then().catch(e){}
}
Copy after login
[Related recommendations]

1.

Free h5 online video tutorial

2.

HTML5 full version manual

3.

php.cn original html5 video tutorial

The above is the detailed content of Share example code for image compression and upload using HTML5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template