canvas and base64

is a base64 encoded binary data format, the same thing as utf8

He, like json, but also before and after the end of the interaction data can identify each other, he is more used to pass data file

Base64 generated in the API js where there are two, one is FileReader, is a canvascanvas

FileReader

<input type="file" onchange="change(this.files[0])">
function change(file){
   var fr = new FileReader()
   fr.onload = function(e) { 
      // 这个就是base64
      console.log( e.target.result );
   }
   // 这个方法传参是一个Blob类型的格式
   fr.readAsDataURL(file)
}

canvas
we use canvas to get content on the canvas
input canvas is a picture, then the picture cut, watermark fight what
the output format of the content on the canvas is base64

// 这个image就是输入
// 除了new,也可以直接取页面上的标签
var image = new Image();

image.onload = function () {
   var w = image.width;
   var h = image.height;
   var canvas = document.createElement('canvas');
   var ctx = canvas.getContext("2d");
   canvas.width = w;
   canvas.height = h;
   ctx.drawImage(image, 0, 0, w, h);
   // 可以在这里添加水印或者合并图片什么的    
   ...
   // 把画布的内容转成base64,这个就是输出
   var base64 = canvas.toDataURL('image/jpeg');
   console.log(base64)
}
// 这个src可以是图片地址,也可以是上面fileReader的base64
image.src = "xxx.jpg";

If you want to compress canvas picture

// 压缩比例
var bili = 0.7;
var base64 = canvas.toDataURL('image/jpeg',bili);

Compatible canvas
canvas api is very unfriendly

  1. Cross-domain issues (see down there are solutions)
  2. Canvas ios system was too small (it needs to do some web version of ps Do not pick)
  3. Camera will rotate (see down there are solutions)

About canvas cross-domain
cross-domain solutions Da God

// 不管画布的输入,即图片的来源是new Image() 还是 document.querySelector()
// 如果图片是外链,产生了跨域,那画布会报错
// Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
// Tainted canvases 【被污染的画布】
// 解决方案是先让后端开启图片支持跨域CORS
// 然后在new Image() 或者 document.querySelector() 之后加上
img.crossOrigin=""

Canvas is too small to obtain base64
solution is not obtained by base64 canvas picture address by requesting, obtaining modify the response header blobformat, and so the blob fileReader turn into base64, the disadvantage is not allowed cross-domain request, the codes

function getBase64(imgUrl) {
   window.URL = window.URL || window.webkitURL;
   var xhr = new XMLHttpRequest();
   xhr.open("get", imgUrl, true);
   // 至关重要
   xhr.responseType = "blob";
   xhr.onload = function () {
    if (this.status == 200) {
         //得到一个blob对象
         var blob = this.response;
         console.log("blob", blob)
         //  至关重要
         let fr = new FileReader();
         fr.onloadend = function (e) {
          let base64 = e.target.result;
          console.log(base64)
         };
         fr.readAsDataURL(blob);
         var img = document.createElement("img");
         img.onload = function (e) {
          window.URL.revokeObjectURL(img.src); // 清除释放
         };
         let src = window.URL.createObjectURL(blob);
         console.log(src)
         img.src = src;
         document.getElementById("xxx").appendChild(img);
    }
  }
  xhr.send();
}
getBase64("xx.png")

About blob
using the above to the knowledge of blob
picture object returned from the input onchange in fact, a File object.
The Blob object is a binary file used for containers and packaging, File inherits from Blob.
FileReader is used to read memory API files, and supports File Blob formats.

FileReader and URL.createObjectURL difference
information from users Nuggets

A difference

  • Some data may be obtained by FileReader.readAsDataURL (file): base64 string
  • Memory may obtain a URL of the current file by URL.createObjectURL (blob)

Difference between the two

  • createObjectURL is performed synchronously (immediately)
  • FileReader.readAsDataURL is executed asynchronously (over time)

Three differences

  • createObjectURL return for a url with hash, and has been stored in memory until the document triggers the unload event (for example: document close) or perform revokeObjectURL be released.
  • FileReader.readAsDataURL base64 contains many characters return, and will consume more memory than the blob url, but will be automatically cleared from memory when not in use (by garbage collection)

Three differences

  • createObjectURL supports all modern browsers from IE10-up
  • FileReader.readAsDataURL also supports all modern browsers from IE10-up

Camera rotation causes and solutions for
information from users Nuggets

Why would rotate pictures from your camera to obtain it?
Because the camera to take pictures from pictures taken of the EXIF (Exchangeable image file format) will set up a default orientation tag
currently only jpeg format images will be

image.png

There are solutions to
get a picture with EXIF.js plug orientationjudge
Lite EXIF.js with DataViewAPI from stackoverflow Code

function getOrientation(file, callback) {
    var reader = new window.FileReader();
    reader.onload = function (e) {

        var view = new window.DataView(e.target.result);
        if (view.getUint16(0, false) != 0xFFD8) {
            return callback(-2);
        }
        var length = view.byteLength, offset = 2;
        while (offset < length) {
            var marker = view.getUint16(offset, false);
            offset += 2;
            if (marker == 0xFFE1) {
                if (view.getUint32(offset += 2, false) != 0x45786966) {
                    return callback(-1);
                }
                var little = view.getUint16(offset += 6, false) == 0x4949;
                offset += view.getUint32(offset + 4, little);
                var tags = view.getUint16(offset, little);
                offset += 2;
                for (var i = 0; i < tags; i++) {
                    if (view.getUint16(offset + (i * 12), little) == 0x0112) {
                        return callback(view.getUint16(offset + (i * 12) + 8, little));
                    }

                }
            } else if ((marker & 0xFF00) != 0xFF00) {
                break;
            } else {
                offset += view.getUint16(offset, false);
            }
        }
        return callback(-1);
    };
    reader.readAsArrayBuffer(file);
}


// 将图片旋转到正确的角度
function resetOrientation(srcBase64, srcOrientation, callback) {
    var img = new Image();
    img.onload = function() {
        var width = img.width,
            height = img.height,
            canvas = document.createElement('canvas'),
            ctx = canvas.getContext("2d");
        // set proper canvas dimensions before transform & export
        if ([5,6,7,8].indexOf(srcOrientation) > -1) {
            canvas.width = height;
            canvas.height = width;
        } else {
            canvas.width = width;
            canvas.height = height;
        }
        // transform context before drawing image
        // -2: not jpeg
        // -1: not defined
        switch (srcOrientation) {
            case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
            case 3: ctx.transform(-1, 0, 0, -1, width, height ); break;
            case 4: ctx.transform(1, 0, 0, -1, 0, height ); break;
            case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
            case 6: ctx.transform(0, 1, -1, 0, height , 0); break;
            case 7: ctx.transform(0, -1, -1, 0, height , width); break;
            case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
            default: ctx.transform(1, 0, 0, 1, 0, 0);
        }
        // draw image
        ctx.drawImage(img, 0, 0);
        // export base64
        callback(canvas.toDataURL('image/jpeg'));
    };
    img.src = srcBase64;
};

Then after rotating the canvas with a right in generating the correct base64, canvas compatibility issue is also very friendly ah

If there is a need on the phone canvas can not do as much as possible, pc client can do a do, canvas album comes with a micro letter is to make the best of the mobile phone side, the micro-channel compatible mobile phones are about to get, and this is why then do someone else's platform web page a good place, a number of API, compatibility is also very good, micro-letter code for "micro-channel public number" articles

Guess you like

Origin www.cnblogs.com/pengdt/p/12037986.html