Mobile album image compression upload based on h5+ API

Source: Internet
Author: User

//female functionfunction App () {}/** * image compression, default proportional compression * @param {Object} path * The path to the PC can be a relative path, but the path that must be passed on the mobile side is the absolute path of the picture storage * @param {object} obj * Obj object has width, height, quality (0-1) * @param {Object} callback * callback function has one parameter, base64 string data*/App.prototype.dealImage=function (path, obj, callback) {varIMG =NewImage (); IMG.SRC=path; Img.onload=function () {varthat = This; //default scaled compression        varW =that.width, H=That.height, scale= w/h; W= Obj.width | |W; H= Obj.height | | (w/Scale ); varQuality =0.7;//default picture quality is 0.7//Build Canvas        varCanvas = document.createelement ('Canvas'); varCTX = Canvas.getcontext ('2d'); //To Create an attribute node        varANW = Document.createattribute ("width"); Anw.nodevalue=W; varAnh = Document.createattribute ("Height"); Anh.nodevalue=h;        Canvas.setattributenode (ANW);        Canvas.setattributenode (Anh); Ctx.drawimage (That,0,0, W, h); //Image quality        if(Obj.quality && obj.quality <=1&& obj.quality >0) {Quality=obj.quality; }        //The smaller the quality value, the more blurry the image is drawn.        varBase64 = Canvas.todataurl ('Image/jpeg', quality); //callback function returns the value of Base64Callback (base64); }}/** * get Picture Post processing callback processing data * @param {object} Delobj * required to process the parameters of the objects * @param {object} CB * Callback function returns the data to be processed, including the source file size, processing After the file size, file name*/APP.PROTOTYPE.DELPHOTOMSG=function (Delobj, CB) {varCamera =Plus.camera.getCamera (); varres = camera.supportedimageresolutions[0]; varFMT = camera.supportedimageformats[0]; var_this = This; varFileobj ={origin: {}, now: {}}; //Callback Object Interface//get the camera to take a picturecamera.captureimage (function (path) {Plus.io.requestFileSystem (Plus.io.PRIVATE_WWW, function (FS) { Fs.root.getFile (Path, {create:true}, Function (Fileentry) {fileentry.file (function (file) {//console.log ("Original File Size:" + file.size/1024 + "KB filename:" +file.name);origin (File.size, file.name); })}) function origin (filesize, filename) {//Mobile image Compression processingPlus.io.resolveLocalFileSystemURL (path, function (entry) {varLocal = Entry.tolocalurl ();//get Local address//image Compression Processing_this.dealimage (local, delobj, function (Base) {FileObj.now.base64Char=Base; FileObj.now.base64Length=Base. Length; FileObj.now.fileSize= (Base. Length/1024x768). ToFixed (2) +"KB"; FileObj.origin.fileSize= (FileSize/1024x768). ToFixed (2) +"KB"; FileObj.origin.filePath=Local; Fileobj.filename=filename;                CB (FILEOBJ); })}}}, function (err) {Console.log ("Get photo error:"+err.message); }, {resolution:res, format:fmt})}/** * * * @param {object} del * requires direct processing of parameter objects * For example: "{width:100, height:100, quality:0.5}" * The default processing is proportional, as long as you set the width or height,quality default 0.7 * @param {Object} options * Picture processing properties Handle file formats multiple select multiple files for Batch processing * For example: {filter: "Image", multiple:true} * @param {Object} callback * callback function returns the corresponding parameter * return Returns an array of objects, including the original file size * For example: obj[0].origin.filesize, Obj[0].now.filesize,obj[0].now.filepath, etc.*/App.prototype.delGalleryImg=function (Del, options, callback) {var_this = This; varFileobj ={now: {}, Origin: {}} plus.gallery.pick (function (Eve) {if(options.multiple) {delmultiple (Eve); //multiple photo processing callback functions}Else{Delsingle (Eve); //single picture processing callback function}},function (Err) {Console.log (Err.message)}, {Filter:options.filter||"Image", Multiple:options.multiple||false    })        //working with multiple picturesfunction Delmultiple (Eve) { for(vari =0, Len = eve.files.length; i < Len; i++){//Console.log (i + ":" + eve.files[i])(Function (i, Len) {//because this is an asynchronous operation, you need to automatically execute the function to pass in the value of index into the function for automatic executionRetValue (Eve.files[i], function (Filepro) {//Console.log (Json.stringify (Filepro))Inner (i, Len, Filepro); })}) (I, Len) }varCbobj = [];//a character array for staging JSON string sessionsfunction Inner (index, Len, result) {//Console.log (Index + "" + json.stringify (Result));Cbobj.push (json.stringify (result));//here, if you push the object directly into the numeric value, there will be the same object element (somehow), so a            if(Cbobj.length = =Len) {                varTempobj = [];//callback an array of objects after parsing the string                 for(vari =0; i < Len; i++) {//iterate through all the files for string parsing                    varobj =Json.parse (Cbobj[i]) tempobj[i]=obj;        } callback (Tempobj); //callback Array Object            }        }    }    //processing a single picturefunction Delsingle (path) {//invoking an internal function callback function for external single image selection processing property callbackRetValue (path, function (Filepro) {callback (FILEPRO);    }); } function RetValue (path, CB) {Plus.io.requestFileSystem (Plus.io.PRIVATE_WWW, function (FS) {fs.ro Ot.getfile (Path, {create:true}, Function (Fileentry) {fileentry.file (function (file) {//console.log ("Original File Size:" + file.size/1024 + "KB filename:" +file.name);origin (File.size, file.name); })            })        })        //callback functionfunction origin (filesize, filename) {//Mobile image Compression processingPlus.io.resolveLocalFileSystemURL (path, function (entry) {varLocal = Entry.tolocalurl ();//get Local address//image Compression Processing_this.dealimage (local, Del, function (Base) {FileObj.now.base64Char=Base; FileObj.now.base64Length=Base. Length; FileObj.now.fileSize= (Base. Length/1024x768). ToFixed (2) +"KB"; FileObj.origin.fileSize= (FileSize/1024x768). ToFixed (2) +"KB"; FileObj.origin.filePath=Local; Fileobj.filename=filename;                CB (FILEOBJ); })            })        }    }    }

This example is based on Hbuilder development, when encountering app mobile photo upload, photo album image compression upload, etc.

Do not like to spray, hope to have this aspect of learning friends more guidance.

Mobile album image compression upload based on h5+ API

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.