js pictures Blob base64 ArrayBuffer achieve various conversion

First, the basic knowledge

Constructor

FileReader() 返回一个新构造的FileReader

Event Processing

FileReader.onabort processing abortevents. This event is triggered when the read operation is interrupted.

FileReader.onload processing loadevents. This event is triggered when the read operation is completed. 

FileReader.onloadstart 处理loadstart事件。该事件在读取操作开始时触发。

FileReader.onloadend 处理loadend事件。该事件在读取操作结束时(要么成功,要么失败)触发。

FileReader.onprogress 处理progress事件。该事件在读取Blob时触发。\

method:

FileReader.readAsArrayBuffer () Once completed, resultwill read the file attribute contains the raw binary data.

FileReader.readAsDataURL () Once completed, resultin the attribute contains a data:Base64 string representing the URL format to read the contents of the file.

FileReader.readAsText () Once completed, resultwill attribute contains a string to represent the content file read.

The Window atoB () method

atoB () method for decoding using the base-64 encoded string.

window . atoB ( encodedStr ) This method returns a string of decoded.

charCodeAt () method

Unicode encoding the charCodeAt () method returns the position of the specified character. The return value is 0 - integer between 65535.
"! Hello world" // in the string, we will return Unicode character encoding position 1: 
var = STR "! The Hello World" 
document.write (str.charCodeAt (1)) 

// output of the code is: 101

  

 

ArrayBuffer 与 Blob

 

ArrayBuffer对象用来表示通用的、固定长度的原始二进制数据缓冲区。

 

Blob (binary large object),二进制大对象,是一个可以存储二进制文件的容器。
Blob是一个大文件,典型的Blob是一张图片或者一个声音文件,由于他们的尺寸,必须使用特殊的方式来处理
var blob = new Blob(dataArr:Array<any>, opt:{type:string});
  • dataArray: array containing the Blob object to be added to, the data can be any multiple ArrayBuffer, ArrayBufferView, Blob, or DOMString object.
  • opt: objects, attributes used to set the Blob object (eg: MIME type)

ArrayBuffer转Blob

    // arraybuffer turn blob is very convenient, as a parameter on the line. 
     
    an ArrayBuffer new new Buffer = var (16) 
    var = new new BLOB Blob ([Buffer]) // NOTE: Always use square brackets enclose

Blob转ArrayBuffer

Here it needs fileReader objects: 
 
var = new new BLOB Blob ([1,2,3,4,5]) 

var = new new Reader the FileReader () 

 reader.readAsArrayBuffer (BLOB) 

reader.onload = function () { 
    the console.log ( this.result) 
} 

 
// console output data is the ArrayBuffer.

ArrayBuffer and Blob, are container binary data, and more ArrayBuffer compared to the bottom, he can go to modify the operation of these binary values ​​between the two is also possible the system conversion.  

Two, js achieve image resources, the various conversion Blob base64 ArrayBuffer

html

<body> 
	<input type="file" id="shangchuan" onchange="filechange()">
	<div class="tup">
		<img id="img" src="">
	</div>
</body>

js 

ArrayBuffer转Blob

function filechange(){
		let files = document.getElementById("shangchuan").files[0];
		let type = files.type
		console.log("files",files)
		geturl(files,type)
	}

	function geturl(files,type){
		let reads = new FileReader();
		reads.readAsArrayBuffer(files);
		reads.onload = function(e){
			console.log(reads.result)
			console.log(new Blob([reads.result],{'type':type}))
			// 注意:里面的this指的就是reads,所以reads.result == this.result
			//document.getElementById("img").src = this.result;
		}
	}

  

BASE64 file transfer

getBase64 function (File, the callback) { 
    var Reader the FileReader new new = (); // the IE10 + 
    var AllowImgFileSize = 2.1 million; // Photo maximum value (in bytes) (2 M = 2097152 B) exceeds 2M upload failures 
    var File = File || $ ( "# shangchuan") get (0) .files [0]; // get the file upload objects. 
    / * 
        the FileList {0: file,. 1: file, length: 2} multiple files 
        file: {name : "fan.jpg", lastModified: 1559019043288 , lastModifiedDate: Tue May 28 2019 12:50:43 GMT + 0800 ( China standard time), webkitRelativePath: "", size: 3,346,145, type: "Image / JPEG"} 
        the FileList { 0: file, 1: file, length: 2} single file 
     * / 
    IF (file) { 

        // read the specified Blob or file object loadend trigger event and is assigned to the base64 encoding picture Result  
        reader.readAsDataURL (file);
        //reader.readAsText(File )
        // asynchronous communication callback function returns 
        reader.onload = function (E) { 
           // var ImgFileSize = reader.result.substring (reader.result.indexOf ( ",") +. 1) .length; base64 code section taken // ( Alternatively is optional, and need to communicate back) 
           ! IF (= 0 && AllowImgFileSize AllowImgFileSize <reader.result.length) { 
                Alert ( 'upload. Please upload images not more than 2M!'); 
                return; 
            } the else { 
                var base64Data reader.result =; 
                // return base64 encoding 
                the callback (base64Data); 
            } 
        } 
    }   
  
}

BASE64 file transfer

function Base64toFile(dataurl, filename) {//将base64转换为文件
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
    }

 

base64 turn blob

 

A method 
function convertBase64UrlToBlob (base64) { var = base64.split type ( ",") [0] .match (/:.? (*); /) [. 1]; // base64 extraction head type as' image / PNG ' var bytes = window.atob (base64.split (', ') [. 1]); // url head removed and converted to byte (atob: encoding btoa: decoding) // handling exceptions, less than the ascii code 0 conversion is more than 0 var = new new ab & an ArrayBuffer (bytes.length); // common, raw binary data buffer target fixed length (bytes.length) a // new new Uint8Array var = IA (bytes.length); for (var I = 0; I <bytes.length; I ++) { ab & [I] = bytes.charCodeAt (I); } the let new new Blob BLOB = ([ab &], {type: type}); the console.log (BLOB ) }

  

Method II 
function convertBase64UrlToBlob (base64) { 
    var = base64.split type ( ",") [0] .match (/:.? (*); /) [. 1]; // base64 extraction head type as' image / PNG '      
    var bytes = window.atob (base64.split (', ') [. 1]); // url head removed and converted to byte (atob: encoding btoa: decoding) 

    // handling exceptions, less than the ascii code 0 conversion is more than 0 
    // ab & var = an ArrayBuffer new new (bytes.length); // common, fixed length (bytes.length) raw binary data buffer object 
    var = IA new new Uint8Array (bytes.length); 
    for (var I = 0; I <bytes.length; I ++) { 
        IA [I] = bytes.charCodeAt (I); 
    } 
    the let new new Blob BLOB = ([IA], {type: type}); 
    the console.log (BLOB ) 
}

blob turn base64   

function blobToBase64(blob, callback) {
    let a = new FileReader();
    a.onload = function (e) { callback(e.target.result); }
    a.readAsDataURL(blob);
}

  

Blob to walk around by the method of the XHR

let xhr = new XMLHttpRequest();
xhr.open("get", "http://mybg.oss-cn-hangzhou.aliyuncs.com/2019031510452423", true);
xhr.responseType = "blob";
xhr.onload = function (res) {
  if (this.status == 200) {
    var blob = this.response;
  }
}
xhr.send();

  

 

Guess you like

Origin www.cnblogs.com/liumingwang/p/12069207.html