Mobile phones take pictures and set pictures to specific sizes. We found some information on the Internet. We can use HTML 5 as a native way or plug-in. Now we can implement them in two ways.
Native mode is mainly used for FileReader
The instance of FileReader has four methods, three of which are used to read files, and the other is interrupt files. Whether reading succeeds or fails, the method does not return the result, but stores it in the result attribute.
1. abort parameter none interrupts reading
2. ReadAs BinaryString parameter file reads the file as binary code
3. readAsDataURL parameter file reads the file as a DataURL
4. readAsText file,[encoding] reads the file as text. This method has two parameters, the second one is the encoding of the text, and the default value is utf-8.
FileReader contains a complete set of event models for capturing the state of the file when it is read
1. Triggered when onabort reads interrupt
2. trigger when onerror error occurs
3. Trigger when onload file reading completes successfully
4. onload end read completion trigger, whether successful or unsuccessful
5. Onload start triggers at the start of reading
6. onprogress Trigger in Read
fr.onload = function() {
this.result; The read results are stored in the result attribute
};
<body> <div id="test-file-info"></div> <div id="test-image-preview"></div> <form action=""><input id="test-image-file" type="file" capture="camera" accept="image/*"> </form> </body>
<style> #test-image-preview { width:100%; height:200px; border:1px solid #ff0000; overflow:hidden; } #test-image-preview canvas{width:100%;} </style>
Note: About the canvas set to 100%, only the size of the display, not the actual size of the canvas.
<script> window.onload=function(){ var fileInput = document.getElementById('test-image-file'); var info = document.getElementById('test-file-info'); var preview = document.getElementById('test-image-preview'); //var img = document.createElement("img"); //preview.appendChild(img); fileInput.addEventListener('change',function(e){ console.log('change...'); preview.innerHTML = ""; //preview.style.backgroundImage=''; if (!fileInput.value){ info.innerHTML = 'No files selected'; return ; } //var file = fileInput.files[0]; var file = e.target.files[0]; var fontSize = file.size/1024/1024; console.log(file.type); // info.innerHTML = file:'+file.name +'<br>'+'size:'+fontSize.toFixed(2) + "M"+'<br>'+' modification:'+file.lastModified Date; if(file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif'){ alert('Not a valid picture file!'); return; } //When the FileReader instance reads successfully, assign the result to the src of the picture var reader = new FileReader(); reader.onload=function(e){ console.log('reader.onload'); var data = e.target.result;//It can also be written as var data = this.result; compress(data); function compress(data){ var img = new Image(); img.src = data; //preview.appendChild(img); var maxW = 640; img.onload = function () { var cvs = document.createElement('canvas'), ctx = cvs.getContext('2d'); if(img.width > maxW) { img.height= maxW / img.width * img.height; img.width = maxW; //img.height = maxH; } cvs.width = img.width; cvs.height = img.height; ctx.clearRect(0, 0, cvs.width, cvs.height); ctx.drawImage(img, 0, 0, img.width, img.height); var dataUrl = cvs.toDataURL('image/jpeg', 1); preview.appendChild(cvs); } //document.body.appendChild(cvs); // Upload Brief } // preview.style.backgroundImage='url('+ data +')'; /// The FileReader instance reads the file as a DataURL format before it can be displayed in the image preview. } reader.readAsDataURL(file); }); }; </script>
Local ResizeIMG4 can also be used, which is more convenient to use, and the image after sensory processing is clearer.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <title>file api</title> <style> #previewImgDiv{width:200px;height:200px;background:#f2f2f2;overflow:hidden;} #previewImgDiv img{width:100%;} .file-input{ position:relative; width:100px; } .file-input button{width:100%;height:28px;line-height:28px;color:#fff;background:#0fd5d3;border:none;} .file-input button:hover{background:#07b9b7;} .file-input button:focus{outline:none;} .file-input input{position:absolute;left:0;top:0;width:100%;height:100%;opacity:0;} .file-input input:hover{cursor:pointer;} </style> </head> <body> <div id="test-file-info"></div> <div id="previewImgDiv">Picture Preview</div> <div class="file-input"> <button class="btn btn-primary file-inner-btn"> //File upload <i class="ion-ios-cloud-upload-outline"> </i> </button> <input type="file" capture="camera" accept="image/*" name="logo" id="file"> </div> </body> <script src="dist/lrz.bundle.js"></script> <script type="text/javascript"> document.querySelector('input').addEventListener('change', function () { // this.files[0] Is a user-selected file lrz(this.files[0], {width: 500}) .then(function (rst) { // Show users the processed pictures (optional) var imgDiv = document.getElementById('previewImgDiv'); var img = new Image(); img.src = rst.base64; //base64 Character string imgDiv.innerHTML =""; imgDiv.appendChild(img); // img.onload = function () { // document.body.appendChild(img); // }; return rst; }) .then(function (rst) { // It's time to upload it to the back end. /* ==================================================== */ // Native ajax uploads code, so it looks a lot, but it's absolutely usable // Other frameworks, such as jQuery's processing of formData, are slightly different. Please go to google, baidu by yourself. var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://localhost:5000/'); xhr.onload = function () { if (xhr.status === 200) { // Upload Success } else { // Handling other situations } }; xhr.onerror = function () { // Handling errors }; xhr.upload.onprogress = function (e) { // Upload progress var percentComplete = ((e.loaded / e.total) || 0) * 100; }; // Adding parameters rst.formData.append('fileLen', rst.fileLen); rst.formData.append('xxx', 'I'm the other parameter.'); // Trigger upload xhr.send(rst.formData); /* ==================================================== */ return rst; }) .catch(function (err) { // In the event of a mistake, the error message can be captured here. // And none of the above will be executed. alert(err); }) .always(function () { // Whether it's success or failure, it's going to be done here. }); }); </script> </html>
The pattern above
#previewImgDiv{width:200px;height:200px;background:#f2f2f2;overflow:hidden;}
#previewImgDiv img{width:100%;}
It's just the size of the display, not the actual size of the picture. The actual size lrz(this.files[0], {width: 500}) is set here.