Share example code for image compression and upload using HTML5
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/*" />
Get the uploaded file when the input file triggers the change event
function addPic(e){ if (typeof FileReader === 'undefined') { return alert('你的浏览器不支持上传图片哟!'); } var files = e.target.files || e.dataTransfer.files; if(files.length > 0){ imgResize(file[0], callback); } }
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('canvas'), ctx = canvas.getContext('2d'); if(window.navigator.userAgent.indexOf('iPhone') > 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('image/jpeg', maxSize.level); convertBlob(window.atob(base64.split(',')[1]), callback); } }; fileReader.readAsDataURL(file); }
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: 'image/jpg'}); } catch (e) { window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder; if(e.name === 'TypeError' && window.BlobBuilder){ var blobBuilder = new BlobBuilder(); blobBuilder.append(buffer); blob = blobBuilder.getBlob('image/jpg'); } } callback(blob) }
HTML5's FormData Object upload datafunction callback(fileResize){
var data = new FormData();
data.append('file', fileResize);
var config = {
headers: {'Content-Types': 'multipart/form-data'}
};
// 这里用的es6语法发起请求,可以无视
axios.post(url, data, config).then().catch(e){}
}
Copy after login[Related recommendations]
1.2. 3. function callback(fileResize){ var data = new FormData(); data.append('file', fileResize); var config = { headers: {'Content-Types': 'multipart/form-data'} }; // 这里用的es6语法发起请求,可以无视 axios.post(url, data, config).then().catch(e){} }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.
