In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to use canvas to compress picture size", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use canvas to compress picture size.
Source of problem
This problem stems from the fact that the size of 2MB is limited by the backend when uploading image files. But surpasses 2MB minute by minute when setting up the camera to take photos. In order not to affect the user experience and functional requirements, the size needs to be compressed at the front end and then transmitted to the backend.
Train of thought analysis
Looking for a lot of information, I found that only canvas can compress the picture.
The principle is roughly as follows: 1, first convert the file file of the picture into baseURL 2, and create an image tag to receive the file to obtain the width, height and proportion of the picture. 3. Create canvas canvas to set the size of the canvas. 4. Draw the picture on canvas. 5. Compress the canvas to get a new baseURL 6 and convert the baseURL back to the file.
Function of premise
Convert file files to base64
/ * * @ param {binary file stream} file * @ param {callback function, return base64} fn * / function changeFileToBaseURL (file,fn) {/ / create read file object var fileReader = new FileReader (); / / return null if (file = = undefined) return fn (null) if file is not defined; / / read file file, the result is Base64-bit fileReader.readAsDataURL (file) FileReader.onload = function () {/ / read base64 var imgBase64Data = this.result; fn (imgBase64Data);}}
Convert base64 to a file stream
/ * convert base64 to file * @ param {baseURL} dataurl * @ param {file name} filename * @ return {file binary stream} * / function dataURLtoFile (dataurl, filename) {var arr = dataurl.split (','), mime = arr [0] .match (/: (. *?); /) [1], bstr = atob (arr [1]), n = bstr.length, u8arr = new Uint8Array (n) While (u8arr -) {u8arr [n] = bstr.charCodeAt (n);} return new File ([u8arr], filename, {type:mime});}
Compression method
/ * canvas compressed image * @ param {parameter obj} param * @ param {file binary stream} param.file required * @ param {target compression size} param.targetSize does not pass initial assignment-1 * @ param {output picture width} param.width does not pass initial assignment-1 Proportional scaling does not need to pass height * @ param {output picture name} param.fileName does not pass the initial assignment image* @ param {compressed image degree} param.quality does not pass the initial assignment 0.92. The value range 0call1 * @ param {callback function} param.succ must be passed * / function pressImg (param) {/ / if there is no callback function, do not execute if (param & & param.succ) {/ / return null if (param.file = = undefined) return param.succ (null) if file is not defined; / / append the initial value param.targetSize = param.hasOwnProperty ("targetSize") to the parameter? Param.targetSize:-1; param.width = param.hasOwnProperty ("width")? Param.width:-1; param.fileName = param.hasOwnProperty ("fileName")? Param.fileName: "image"; param.quality = param.hasOwnProperty ("quality")? Param.quality: 0.92; var _ this = this; / / get the file type var fileType = param.file.type; / / console.log (fileType) / / image/jpeg if (fileType.indexOf ("image") = =-1) {console.log ('Please select the picture file ^ _ ^'); return param.succ (null) } / / if the current size is smaller than the target size, directly output var size = param.file.size; if (param.targetSize > size) {return param.succ (param.file);} / / read the file file, and the result is Base64-bit changeFileToBaseURL (param.file,function (base64) {if (base64) {var image = new Image (); image.src = base64 Image.onload = function () {/ / get the aspect ratio var scale = this.width / this.height; / / console.log (scale); / / create a canvas var canvas = document.createElement ('canvas'); / / get the context var context = canvas.getContext (' 2d') / / get the compressed image width. If width is-1, the default image width is canvas.width = param.width =-1? This.width: param.width; / / gets the height of the compressed image. If width is-1, the default height of the original image is canvas.height = param.width =-1? This.height: parseInt (param.width / scale); / / draw the picture onto canvas context.drawImage (image, 0,0, canvas.width, canvas.height); / / compress the image to get a new base64Url var newImageData = canvas.toDataURL (fileType,param.quality); / / convert base64 to file stream var resultFile = dataURLtoFile (newImageData,param.fileName) / / it is judged that if the targetSize is limited and the compressed image size is larger than the target size, the error if (param.targetSize! =-1 & & param.targetSize < resultFile.size) {console.log ("picture upload size is too large, please upload ^ _ ^ again"); param.succ (null) } else {/ / return file stream param.succ (resultFile);});}}
Method use
The size of the file is in bytes, so we need to convert the required size into bytes. 1 byte is 1byte. 1KB = 1024B. 1MB = 1024 * 1024B.
/ / get url$ ("# fileImg") .on ('change',function () {pressImg ({file:this.files [0], targetSize:2 * 1024 * 1024, quality:0.5, width:600, succ:function (resultFile) {/ / if not null or if (resultFile) {/ / TODO})}) At this point, I believe you have a deeper understanding of "how to use canvas to compress picture size". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.