HTML5 mobile development image compression upload function,

Source: Internet
Author: User

HTML5 mobile development image compression upload function,

H5 activities are very common. One of them is to allow users to upload images for participation. When uploading images on mobile devices, users generally upload images in mobile phone photo albums. Nowadays, the quality of mobile phones is getting higher and higher. Generally, the size of a single photo is around 3 M. Direct uploads consume a lot of traffic and the user experience is poor. Therefore, local compression must be performed before upload.

Next, we will summarize the function of compressing and uploading images during the development of the h5 activity, mark the pitfalls that have been step on, and share them with you:

Little white zone

If you have no idea about uploading images to mobile devices, you need to add the FileReader, Blob, and FormData concepts.

1. FileReader

Definition

With the FileReader object, web applications can asynchronously read files (or raw data buffering) stored on users' computers, you can use a File object or Blob Object to specify the File or data to be processed.

Method

Event Handler

Use

var fileReader = new FileReader();fileReader.onload = function() {    var url = this.result;}//orfileReader.onload = function(e) {    var url = e.target.result;}

2. Blob

BLOB (binary large object), a large binary object, is a container that can store binary files.

3. FormData

Using the FormData object, you can use a series of key-value pairs to simulate a complete form, and then use XMLHttpRequest to send this "form ".

Question

Compression and uploading of mobile images:

1) input file: uploads an image and uses FileReader to read the uploaded image;

2) input image data to the img object, draw the img to the canvas, and compress the image using canvas. toDataURL;

3) Get the compressed base64 Format Image Data, convert it to binary, insert formdata, and submit formdata through xmlHttpRequest;

1. retrieve image data

FileEle. onchange = function () {if (! This. files. length) return; // The following is a single graph var _ ua = window. navigator. userAgent; var _ simpleFile = this. files [0]; // determines whether the image is an if (! /\/(? : Jpeg | png | gif)/I. test (_ simpleFile. type) return; // plug-in exif. js gets the direction information of the ios image var _ orientation; if (_ ua. indexOf ('iphone ')> 0) {EXIF. getData (_ simpleFile, function () {_ orientation = EXIF. getTag (this, 'orientation');} // 1. read the file and use FileReader to convert the image file to DataURL, that is, the url starting with data: img/png; base64, which can be directly placed in the image. in src; var _ reader = new FileReader (), _ img = new Image (), _ url; _ reader. onload = function () {_ url = this. result; _ img. url = _ url; _ img. onload = function () {var _ data = compress (_ img); uploadPhoto (_ data, _ orientation) ;};_reader. readAsDataURL (_ simpleFile );};

2. compress the image

/*** Calculate the image size and compress it according to the size * 1. the IMG uses exif. js * 2. android UC browser does not support new Blob (), use BlobBuilder * @ param {Object} _ img image * @ param {Number} _ orientation photo information * @ return {String} compressed base64 Format Image */function compress (_ img, _ orientation) {// 2. the calculation conforms to the high value of the target size and width. If the width and height of the uploaded image are greater than the target image, the image is compressed to the target image. If one side is smaller than the other side, the image is enlarged to the other side. Var _ goalWidth = 750, // target width _ goalHeight = 750, // target height _ imgWidth = _ img. naturalWidth, // Image Width _ imgHeight = _ img. naturalHeight, // Image Height _ tempWidth = _ imgWidth, // The temporary width after being enlarged or reduced _ tempHeight = _ imgHeight, // The temporary width after resizing _ r = 0; // compression ratio if (_ imgWidth ===_ goalWidth & _ imgHeight ===_ goalHeight) {} else if (_ imgWidth> _ goalWidth & _ imgHeight> _ goalHeight) {// the width and height of the target image are greater than those of the target image. equi compression is required: _ r = _ imgWidth/_ goalWidth; if (_ I MgHeight/_ goalHeight <_ r) {_ r = _ imgHeight/_ goalHeight;} _ tempWidth = Math. ceil (_ imgWidth/_ r); _ tempHeight = Math. ceil (_ imgHeight/_ r);} else {if (_ imgWidth <_ goalWidth & _ imgHeight <_ goalHeight) {// width and height are smaller than _ r = _ goalWidth/_ imgWidth; if (_ goalHeight/_ imgHeight <_ r) {_ r = _ goalHeight/_ imgHeight ;}} else {if (_ imgWidth <_ goalWidth) {// The width is less than _ r = _ goalWidth/_ imgWidth;} else {// The height is less than _ r = _ goalHeight/_ imgHeight; }}_ tempWidth = Math. ceil (_ imgWidth * _ r); _ tempHeight = Math. ceil (_ imgHeight * _ r);} // 3. crop the image by using canvas. After the image is scaled in or out, the center is cropped by var _ canvas = e. _ $ get ('canvas-clip'); if (! _ Canvas. getContext) return; var _ context = _ canvas. getContext ('2d '); _ canvas. width = _ tempWidth; _ canvas. height = _ tempHeight; var _ degree; // ios bug. The iphone may encounter an image Direction Error. switch (_ orientation) {// The iphone landscape shot, in this case, the home Key is taken on the case 3: _ degree = 180; _ tempWidth =-_ imgWidth; _ tempHeight =-_ imgHeight; break; // iphone portrait screen, at this time, the home Key is at the bottom (normally in the direction of the mobile phone) case 6: _ canvas. width = _ imgHeight; _ canvas. height = _ imgWidth; _ degree = 90; _ TempWidth = _ imgWidth; _ tempHeight =-_ imgHeight; break; // when shooting an iphone portrait screen, the home Key is above case 8: _ canvas. width = _ imgHeight; _ canvas. height = _ imgWidth; _ degree = 270; _ tempWidth =-_ imgWidth; _ tempHeight = _ imgHeight; break;} if (window. navigator. userAgent. indexOf ('iphone ')> 0 &&!! _ Degree) {_ context. rotate (_ degree * Math. PI/180); _ context. drawImage (_ img, 0, 0, _ tempWidth, _ tempHeight);} else {_ context. drawImage (_ img, 0, 0, _ tempWidth, _ tempHeight);} // toDataURL method, which can be obtained in the format of "data: image/png; base64, * ** "base64 image information; var _ data = _ canvas. toDataURL ('image/jpeg '); return _ data ;}

3. upload images

/*** Upload an image to NOS * @ param {Object} _ blog Blob format * @ return {Void} */function uploadPhoto (_ data) {// 4. obtain the image information in the canvas // window. the atob method converts an image in base64 format to a binary string. If the converted value is directly assigned to Blob, an error is returned. Uint8Array conversion is required. Finally, a Blob object is created; _ data = _ data. split (',') [1]; _ data = window. atob (_ data); // If ArrayBuffer is not used, the image format sent to the server is [object Uint8Array]. Upload Failed... var _ buffer = new ArrayBuffer (_ data. length); var _ ubuffer = new Uint8Array (_ buffer); For (var I = 0; I <_ data. length; I ++) {_ ubuffer [I] = _ data. charCodeAt (I);} // The Android UC browser does not support new Blob (). Use BlobBuilder var _ blob; try {_ blob = new Blob ([_ buffer], {type: 'image/jpeg '});} catch (ee) {window. blobBuilder = window. blobBuilder | window. webKitBlobBuilder | window. export blobbuilder | window. MSBlobBuilder; if (ee. name = 'typeerror' & window. blobBuilder) {var _ bb = new BlobBuilder (); _ Bb. append (_ buffer); _ blob = _ bb. getBlob ('image/jpeg ');} var _ suffix = 'jpg'; if (_ blob. type = 'image/jpeg ') {_ suffix = 'jpg';} // obtain noen en this. _ cache. _ $ requestDWRByGet ({url: 'imagebean. genTokens ', param: [_ suffix, '', '1'], onload: function (_ tokens) {_ tokens = _ tokens | []; var _ token = _ tokens [0]; if (! _ Token |! _ Token. objectName |! _ Token. uploadToken) {alert ('token acquisition failed! '); Return false;} // upload the image to NOS var _ objectName = _ token. objectName, _ uploadToken = _ token. uploadToken, _ bucketName = _ token. bucketName; var _ formData = new FormData (); _ formData. append ('object', _ objectName); _ formData. append ('x-nos-token', _ uploadToken); _ formData. append ('file', _ blob); var _ xhr; if (window. XMLHttpRequest) {_ xhr = new window. XMLHttpRequest ();} else if (window. activeXObject) {_ xhr = new ActiveXObject ("Microsoft. XMLHTTP ");} _ xhr. onreadystatechange = function () {if (_ xhr. readyState = 4) {if (_ xhr. status> = 200 & _ xhr. status <300) | _ xhr. status = 304) {var _ imgurl =" http://nos.netease.com/ "+ _ BucketName +"/"+ _ objectName + "? ImageView "; var _ newUrl = mb. x. _ $ imgResize (_ imgurl, 750,750, 1, true); window. location. href =' http://www.lofter.com/act/taxiu?op=effect&originImgUrl= '+ _ NewUrl ;}}; _ xhr. open ('post ',' http://nos.netease.com/ '+ _ BucketName, true); _ xhr. send (_ formData );}});}

Plug-in used to determine the direction of an iphone image: exif

The above is a small part of the HTML5 mobile development image compression upload function, to achieve a simulated background data login effect, I hope to help you, if you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

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.