APICloud (10): Image cropping function

The function of uploading avatars is used in the project, so it needs to be cut according to the actual situation. The specific code is as follows:

1. Event trigger :

The uploadHead() event is triggered when the avatar is clicked, and options pop up from the bottom - album, photo - let choose,

Then call api.getPicture() and set the value of sourceType according to the selection,

After selecting the picture, get the picture path and pass it to the openImageClipFrame() method, and the openImageClipFrame() method opens the cropped frame

//This method is used to upload the image
function uploadHead(){	
	//The pop-up box lets you choose whether to take a photo or choose from the album
	api.actionSheet({
		title: 'Select Avatar',
	    cancelTitle: 'Cancel',
	    //destructiveTitle: 'Red warning button',//The title of the red warning button, generally used to do some operations such as deletion
	    buttons: ['Take photo', 'Select from album']
    }, function (ret, err) {
    	//ret.buttonIndex: 1, shoot 2, select 3 from album, cancel
    	switch(ret.buttonIndex){
    		case 1:{getPictureBySourceType(1);break;}//拍摄
    		case 2:{getPictureBySourceType(2);break;}break;//Select from album
    		case 3:return false;//Cancel
    	}
    });
}

/**
 *This method is used to take pictures or get pictures from the album
 * @param source: 1-shoot 2-album
 *  **/
function getPictureBySourceType(source){
	var sourceType = "camera";
	if(source==2){sourceType="library";}
	
	api.getPicture({
	    sourceType: sourceType,//Image source type, get pictures from albums, picture libraries or cameras, options: camera/library/album default library
	    encodingType: 'png',//return the image type, jpg or png, the default value png
	    mediaValue: 'pic',//media type, picture or video, options: pic-picture video-video all-picture and video, Android does not support, the default pic
	    destinationType: 'url',//return data type, specify the return image address or the image string encoded by base64, optional: base64/url
	    allowEdit: false,//Whether you can edit the picture after selecting it, support iOS and some Android phones, the default value is false
	    quality: 100,//image quality, only for jpg format images (0-100 integer)
	    //targetWidth: 70,//The width of the compressed image, the image will be proportional to this width, the default value: the original image width
	    //targetHeight: 70,
	    saveToPhotoAlbum: false//Whether to save to the album after taking a photo or recording a video, the default value is false
	}, function (ret, err) {
	    if (ret) {
	        if(ret.data.length>0){//When the shooting is completed and canceled, this method will be returned, but ret.data is empty
		        //alert(ret.data);
		        //clipImage(ret.data);//Pop up the crop box for cropping
		        openImageClipFrame(ret.data);//This method is used to open the image cropping page
	        }            
        }    
	});   
}
//Open the image crop page
function openImageClipFrame(img_src){
    api.openFrame({
            name : 'imageClipFrame',
            scrollToTop :true,
            allowEdit : true,
            url : 'imageClipFrame.html',
            rect : {
                    x : 0,
                    and : 0,
                    w : api.winWidth,
                    h : api.winHeight,
            },
            animation : {
                  type : "reveal", //Animation type (see animation type constants for details)
                  subType : "from_right", //animation subtype (see animation subtype constants for details)
                  duration : 300
            },
            pageParam : {
                img_src : img_src
            },
            vScrollBarEnabled : false,
            hScrollBarEnabled : false,
            //Whether the page bounces for pull-down refresh
            bounces : false
    });
}

2. Crop the static page and css of the page :

<style>
	* { margin:0;padding:0;}
	ul,li{list-style-type:none; margin:0;padding:0;}
                        
    #foot_div {
            display: block;
            bottom: 0px;
            min-width: 200px;
            line-height: 30px;
            width:100%;
            position: fixed;
            text-align: center;
            color: #fff;
            background: #000;
     }
     #foot_div ul {width:99%;margin:0 auto;}
	 #foot_div li{width:33%;float:left;}
	 #foot_div ul li:nth-of-type(1){text-align:left;}
     #foot_div ul li:nth-of-type(2){text-align:center;}
	 #foot_div ul li:nth-of-type(3){text-align:right;}
</style>

<body>
	<div id="foot_div">   
		<ul>
			<li onclick="back();">取消</li>
			<li onclick="resetImageClip();">重置</li>
			<li onclick="saveImageClip();">选取</li>
		</ul>
	</div>
</body>

3. Save the picture and upload the picture code :

was FNImageClip;
	var BASE_IMG_HEAD_TEMP_PATH="fs://imageClip/result.png";
		
	apiready = function(){
		var img_src = api.pageParam.img_src;
		FNImageClip = api.require('FNImageClip');
		openImageClip(img_src);
    };
	// crop the avatar
	function openImageClip(img_src){
        var rect_w = api.winWidth;
        var rect_h = api.winHeight;
        var clip_w = parseInt(rect_w - 2);
        var clip_y = parseInt((rect_h - clip_w - 30) / 2);
        FNImageClip.open({
            rect: {
                x: 0,
                y: 0,
                w: rect_w,
                h: rect_h - 30
            },
            srcPath: img_src,
            style: {
                    //(Optional) String type; image crop control mask layer background, support rgb, rgba, #; default: #888
			mask: 'rgba(0,0,0,.7)',
			clip: {
			    //(Optional) Number type; the width of the clipping area, when the appearance is circular, w is the radius; default: rect.w / 2
				w: clip_w,
				//(Optional) Number type; the height of the clipping area, when the appearance is circular, h is invalid; default: w
				h: clip_w,
				x: 0,
				y: clip_y,
				borderColor: '#0f0',
				borderWidth: 1,
				//(Optional) String type; the shape of the cropping area, supports circular | rectangle; default: rectangle
				appearance: 'rectangle'
			    }
			},
			mode : 'clip',
			fixedOn: api.frameName
			}, function (ret, err) {        
			 // alert (ret.status);         
		});
	}	
	//return to application page
    function back() {
        closeImageClip();
        api.closeFrame({
            name : 'imageClipFrame'
        });
    }
           
    //Close the clipping component
    function closeImageClip(){
       FNImageClip.close();
    }
           
    // reset the crop component
    function resetImageClip(){
         FNImageClip.reset();
    }
    
    //Save the cropped image        
    function saveImageClip(){
        FNImageClip.save({
            destPath: BASE_IMG_HEAD_TEMP_PATH,
            copyToAlbum: false,
            quality: 1
        }, function (ret, err) {
            if(err) {
                api.toast({
                    msg: 'The server is busy, please try again later'
                });
            }else{
                 //do file upload
                 uploadTheHead (ret.destPath);
            }      
        });
    }
            
    //This method is used to upload the file
    function uploadTheHead(img_str){
    	api.showProgress({
    		title: 'The avatar is uploading',
			modal: true
        });
        img_str="\"file1\":\""+img_str+"\"";
        img_str = eval('('+("{"+img_str+"}")+')');
    	api.ajax({
		    url:$api.getStorage("url"),
		    method:'post',
		    dataType:'text',
		    data:{
		    	values:{
		        	'user_id':$api.getStorage("u_id"),
		        	'user_name':$api.getStorage("u_name"),
		        	'time':new Date().getTime()
		    	},	    	
		    	files:img_str
		    }
		}, function (ret, err) {
			api.hideProgress();//Hide the progress prompt box
		    $api.setStorage("u_path",ret);//The image path returned by ajax is stored in sorage to display the avatar
		    //return to application interface
		    closeImageClip();//Close the current image clipping function
            api.closeFrame({
                name : 'imageClipFrame'
            });
            api.execScript({
            	name:'my_win',//Refresh the window where the avatar is located
                script: 'refreshWin();'
            });
		});
    }

Attention :

a. BASE_IMG_HEAD_TEMP_PATH is a name that you define at will, and the content in it can also be defined at will. But it must be set, because you must give the cropped image a place to save and then upload it to the server.

b. Sometimes the picture is very clear when selecting the picture, but the picture is very blurred when the page is cropped after the selection. This is actually not the problem of the FNImageClip module but the problem of api.getPicture(). Set the quality to 100, targetWidth and targetHeight. attributes are not added .

The quality attribute is used to set the quality of the image, from 0-100, the default is 50, which is already very blurred, after setting it to 100, what you choose to crop is what you see.

The two properties targetWidth and targetHeight are not added, it is not that they are not copied, but that these two properties are not added when calling api.getPicture(), let it default. These two attributes are used to refer to the size of the compressed image. How to refer to and how to calculate the official website is described in detail, but the calculated result is always different from the value we set, so it is best not to use it.

 

Reference link:

1、http://community.apicloud.com/bbs/forum.php?mod=viewthread&tid=32311&extra=&page=1

2、http://docs.apicloud.com/Client-API/Func-Ext/FNImageClip

good luck!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326511463&siteId=291194637