About official account H5 compression method

Posted by marknt on Tue, 01 Feb 2022 23:29:20 +0100

preface

Development of official account H5 uploading pictures and compressing method based on uni-app

thinking

Upload pictures

We should be clear that there are three ways to display pictures: file (file stream), bolb (local stream) and Base64 (binary stream)

file

The File interface provides information about the File and allows JavaScript in the web page to access its content.

Usually, the File object comes from the FileList object returned after the user selects a File on an element, the DataTransfer object generated by free drag and drop operation, or the mozGetAsFile() API on HTMLCanvasElement. In Gecko, privileged code can create File objects that represent any local File without user interaction

The File object is a special type of Blob and can be used in the context of any Blob type. For example, FileReader, URL Createobjecturl(), createimagebitmap(), and XMLHttpRequest Send() can handle Blob and File.

blob

A blob object represents an immutable, raw data class File object. It refers to the local temporary address. Blob does not necessarily represent data in JavaScript native format. Based on blob, the File interface inherits the function of blob and extends it to support files on the user's system.

base64

base64 is a set of similar binary to text encoding rules, which enables binary data to be expressed in ASCII string format after being interpreted into the representation of radio-64. The word base64 comes from a MIME data transmission code. If it is base64 of the picture, it can be used for compression

They can be transformed into each other. When uploading pictures, they usually get blob and file

Picture compression

For compression, we choose canvas for compression. The toDataURL method will automatically convert the image to base64

Use canvas to compress picture * code

export function translate(imgData, callback) {
	var img = new Image();
	img.src = imgData.tempFilePaths[0];
	img.onload = function() {
		var that = this;
		var h = that.height; // Ensure the same height after compression		
		var w = that.width;  // Ensure the same width after compression
		var canvas = document.createElement('canvas'); //Create canvas
		var ctx = canvas.getContext('2d'); //2d format
		// Create the width and height attribute and create a new attribute node for canvas
		var anw = document.createAttribute("width");
		anw.nodeValue = w;
		var anh = document.createAttribute("height");
		anh.nodeValue = h;
		canvas.setAttributeNode(anw);
		canvas.setAttributeNode(anh);
		ctx.drawImage(that, 0, 0, w, h); // Painting into canvas		
		var quality = 0.1; //You can choose the quality of the picture from 0 to 1. If the value range is exceeded, the default value of 0.92 will be used. Other parameters are ignored
		var base64 = canvas.toDataURL('image/jpeg', quality);//Convert to base64
		canvas = null;
		var res = dataURLtoFile(base64,imgData.tempFiles[0].name);
		callback(res);
	}
} 

base64 to file * code

function base64ToFile(dataurl, filename) { //Convert base64 to file
	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 to blob * code

function base64toBlob(dataurl) { //base64 to blob
    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 Blob([u8arr], { type: mime });
}

blob to base64 * code

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

In addition to the above methods, you can also use canvas to convert to base64

blob to file * code

Method 1:

function blobToFile(blob, fileName, type) {  //blob to file
    let files = new window.File([blob], fileName, {type: type})
    return files
}

Method 2:

function blobToFile(blob, fileName){  // blob to file
	blob.lastModifiedDate = new Date();  
	blob.name = fileName;  
	return blob;
};

file to bse64 * code

function fileToBase64(file){   //file to bse64
	let reader = new FileReader();  
	reader.readAsDataURL(file);  
	reader.onload = function (e) {    
		return e.target.result  
	}
}

Topics: Javascript H5