JS compression upload Image

Source: Internet
Author: User
JS compression upload image JS compression upload Image

/*** @ Date: 2016/11/17 0017 * @ Time: * @ Author: lxbin ** Created with JetBrains WebStorm .*//*** http://leonshi.com/2015/10/31/html5-canvas-image-compress-crop/ * http://jafeney.com/2016/08/11/20160811-image-upload/ * // *** Read the file * @ param file object * @ return {Promise} */function readFileAsync (file) {return new Promise (resolve, reject) ==>{ const reader = new FileReader () reader. onload = e => resolve(readFile.tar get. result) reader. onerror = e => reject (new Error ('could not read file') reader. readAsDataURL (file)}/*** load image * @ param url image address * @ return {Promise} */function loadImageAsync (url) {return new Promise (resolve, reject) => {const image = new Image () image. onload = () => resolve (image) image. onerror = () => reject (new Error ('could not load image at '+ url) image. src = url})}/*** convert the image dataUri of base64 to Blob * @ param dataURI * @ return {*} */function dataURItoBlob (dataURI) {// convert base64 to raw binary data held in a string // doesn' t handle URLEncoded DataURIs-see SO answer #6850276 for code that does this var byteString = atob (dataURI. split (',') [1]); // separate out the mime component var mimeString = dataURI. split (',') [0]. split (':') [1]. split (';') [0] // write the bytes of the string to an ArrayBuffer var AB = new ArrayBuffer (byteString. length); var ia = new Uint8Array (AB); for (var I = 0; I <byteString. length; I ++) {ia [I] = byteString. charCodeAt (I);} // write the ArrayBuffer to a blob, and you're done var blob = new Blob ([AB], {type: mimeString}); return blob; // Old code // var bb = new BlobBuilder (); // bb. append (AB); // return bb. getBlob (mimeString);}/*** convert image to Blob * @ param image object * @ param quality image quality (between 0 and 1) * @ param scale (between 0 and 1) * @ return {Promise} */function imageToBlob (image, quality, scale) {return new Promise (resolve, reject) ==>{ try {let canvas = document. createElement ('canvas ') canvas. width = image. naturalWidth * scale canvas. height = image. naturalHeight * scale while (canvas. width> = 3264 | canvas. height> = 2448) {// base64 cannot be generated when the value is exceeded. canvas on IOS. width = canvas. naturalWidth * scale canvas. height = canvas. naturalHeight * scale} let ctx = canvas. getContext ('2d '). drawImage (image, 0, 0, canvas. width, canvas. height) // Method 1: lower version has lower compatibility // canvas. toBlob (function (blob) {// console. group ('[Leo] file compress to blob') // console. log ('file type => '+ file. type) // console. log ('file size => '+ (file. size/1024/1024 ). toFixed (2) + 'M') // console. log ('blob quality => '+ quality) // console. log ('blob size => '+ (blob. size/1024/1024 ). toFixed (2) + 'M') // console. groupEnd () // resolve (blob) //}, 'image/jpeg ', quality) // Method 2: var base64 = canvas. toDataURL ('image/jpeg ', quality); var blob = dataURItoBlob (base64); console. group ('[Leo] file compress to blob') console. log ('file type => '+ file. type) console. log ('file size => '+ (file. size/1024/1024 ). toFixed (2) + 'M') console. log ('blob quality => '+ quality) console. log ('blob size => '+ (blob. size/1024/1024 ). toFixed (2) + 'M') console. groupEnd () resolve (blob);} catch (e) {reject (new Error ("Image cocould not convert to blob:" + e ))}})} /*** Ajax upload ** @ param uri the Action address for uploading * @ param file object * @ return {Promise} */function uploadFile (uri, file) {return new Promise (resolve, reject) =>{ let xhr = new XMLHttpRequest () if (xhr. upload) {xhr. upload. addEventListener ("progress", (e) => {// process the upload progress if (e. lengthComputable) {let percent = (e. loaded/e. total * 100 ). toFixed (2) + '%' console. log ("uploading (" + percent + ")"); // TODO: Display in DOM} else {console. log ('unable to compute ') ;}, false)} xhr. onreadystatechange = (e) => {// if (xhr. readyState = 4) {if (xhr. status = 200) {resolve (xhr. responseText) // upload successful} else {reject (xhr. responseText) // handle upload errors} xhr. open ("POST", uri, true) // start to upload let form = new FormData () form. append ("filedata", file) xhr. send (form)}/*** Upload file * @ param file object * @ param quality image quality (between 0 and 1) * @ param scale scaling ratio (between 0 and 1) */export default async function fileUpload (file, quality, scale) {try {let fileUrl = await readFileAsync (file) let image = await loadImageAsync (fileUrl) let blob = await imageToBlob (image, quality, scale) let upload = await uploadFile (blob) return upload} catch (e) {console. log ('file upload failed ')}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.