jQuery+PHP Upload Cut Pictures

Keywords: JQuery PHP Firefox less


Here is a simple example of jquery image preview + clipping. The principle is to get the information to be clipped at the front end, such as aspect ratio, clipping coordinates, upload the picture and then cut it in php at the back end.

jquery code (must be introduced at the end)

        function showCutImg(showImg){

            var showImg = $(showImg);

            var changeInput = showImg.parents('.showImgDiv').siblings('.CutImage');

            var size = changeInput.siblings('.imgCoord').attr('ratio').split('*');

            var needWidth = size[0];

            var needHeight = size[1];

            var ratio = parseInt(needWidth)/parseInt(needHeight);

            ratio = parseFloat(ratio.toFixed(2));

            var thisFullDiv = showImg.parent();

            var coordArr = changeInput.siblings('.imgCoord').val().split(',');

            thisCutImgWidth = showImg.width();
            thisCutImgHeight = showImg.height()

            thisFullDiv.css('width',thisCutImgWidth);
            thisFullDiv.css('height',thisCutImgHeight);

            if((thisCutImgWidth/thisCutImgHeight)>=ratio){
                var thisCutDivHeight = thisCutImgHeight;
                var thisCutDivWidth = thisCutDivHeight*ratio;
            }else{
                var thisCutDivWidth = thisCutImgWidth;
                var thisCutDivHeight = thisCutDivWidth/ratio;
            }

            var hideWidth = (thisFullDiv.width()-thisCutDivWidth)/2;

            showImg.siblings('.hideImgLeft').width(hideWidth);
            showImg.siblings('.hideImgRight').width(hideWidth);

            var hideHeight = (thisFullDiv.height()-thisCutDivHeight)/2;

            showImg.siblings('.hideImgTop').width(thisCutDivWidth);
            showImg.siblings('.hideImgBottom').width(thisCutDivWidth);

            showImg.siblings('.hideImgTop').height(hideHeight);
            showImg.siblings('.hideImgBottom').height(hideHeight);

            if(hideWidth>0){
                var cutRatioX = thisCutImgWidth/hideWidth;
            }else{
                var cutRatioX = 0
            }

            if(hideHeight>0){
                var cutRatioY = thisCutImgHeight/hideHeight;
            }else{
                var cutRatioY = 0;
            }

            var coord = needWidth+'#'+needHeight+'#'+(cutRatioX)+'#'+(cutRatioY);

            if(coordArr!=''){
                coordArr.push(coord);
            }else{
                coordArr = [coord];
            }

            changeInput.siblings('.imgCoord').val(coordArr);
            $('.fullDiv').on('mousedown',function(e){
                var me = $(this);

                var changeInput = me.parent().siblings('.CutImage');

                var index = me.attr('index');

                var oldx = e.pageX;
                var oldy = e.pageY;

                var imgleft = me.children('.cutImg').position().left;
                var imgtop = me.children('.cutImg').position().top;

                var maxw = me.children('.hideImgLeft').width();
                var maxh = me.children('.hideImgTop').height();

                var goordArr = changeInput.siblings('.imgCoord').val().split(',');

                var cutDivSize = goordArr[index].split('#');

                $(document).mousemove(function(e){
                    var newx = e.pageX;
                    var newy = e.pageY;

                    var movex = newx - oldx;
                    var movey = newy - oldy;

                    var x = movex + imgleft;
                    var y = movey + imgtop;

                    if(Math.abs(x)>maxw){
                        if(x>0) x = maxw;
                        if(x<0) x = -maxw;
                    }

                    if(Math.abs(y)>maxh){
                        if(y>0) y = maxh;
                        if(y<0) y = -maxh;
                    }

                    me.children('.cutImg').css('left',x+'px');
                    me.children('.cutImg').css('top',y+'px');

                    if(parseInt(maxw - x)>0){
                        var cutRatioX = me.children('.cutImg').width()/parseInt(maxw - x);
                    }else{
                        var cutRatioX = 0;
                    }

                    if(parseInt(maxh - y)>0){
                        var cutRatioY = me.children('.cutImg').height()/parseInt(maxh - y)
                    }else{
                        var cutRatioY = 0;
                    }

                    var cutImgPo = (cutRatioX) +'#'+ (cutRatioY);

                    var coordVal = cutDivSize[0]+'#'+cutDivSize[1]+'#'+cutImgPo;

                    goordArr[index] = coordVal;

                    changeInput.siblings('.imgCoord').val(goordArr);


                });
            });


            $(document).on('mouseup',function(e){
                $(document).unbind('mousemove');
            });
        }



        $(".CutImage").change(function(){

            $(this).siblings('.imgCoord').val('');

            if($(this).prop('multiple')!=true){        //Determine whether to upload multiple files
                var objUrl = getObjectURL1(this.files[0]) ;

                var showImgWidth = $(this).siblings('.showImgDiv').attr('showImgWidth');

                if(!showImgWidth)
                {
                    showImgWidth = '150';
                }

                if (objUrl) {
                        html = '';
                        html += '
'; html += '
'; html += '
'; html += '
'; html += '
'; HTML +=''px'"onload=" showCutImg (this), "class=" cutImg "class=" imgshover "src="'+objUrl+' "alt=" picture loading failure "/>'; html += '
'; $(this).siblings('.showImgDiv').html(html); } }else{ var objUrl = getObjectURL2($(this).get(0).files); if (objUrl) { var showImgWidth = $(this).siblings('.showImgDiv').attr('showImgWidth'); if(!showImgWidth) { showImgWidth = '150'; } var html = ''; for(var i=0;i'
'" class="fullDiv">'; html += '
'; html += '
'; html += '
'; html += '
'; HTML +=''px'"onload=" showCutImg (this), "class=" cutImg "class=" imgshover "src="'+objUrl [i]+' "alt=" picture loading failure "/>'; html += '
'; // Modify the width style of the img tag to change the size of the preview } $(this).siblings('.showImgDiv').html(html); } //$('.fullDiv').css('float','left'); } }) ; // Create a url that can be accessed to the file function getObjectURL1(file) { var url = null ; if (window.createObjectURL!=undefined) { // basic url = window.createObjectURL(file) ; } else if (window.URL!=undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file) ; } else if (window.webkitURL!=undefined) { // webkit or chrome url = window.webkitURL.createObjectURL(file) ; } return url ; } // Create a url that can be accessed to the file function getObjectURL2(file) { var url = new Array(); if (window.createObjectURL!=undefined) { // basic for(var i=0;ielse if (window.URL!=undefined) { // mozilla(firefox) for(var i=0;ielse if (window.webkitURL!=undefined) { // webkit or chrome for(var i=0;ireturn url ; }

html code (which should be placed at the same level)


<input class="CutImage" type="file" name="img" />


<input ratio="100*100" type="hidden" class="imgCoord" name="imgCoord">


<div showImgWidth="100" class="showImgDiv">div>

php code

/*Picture upload code just below for image clipping*/

/**
 * [cut_img Picture clipping function]
 * Author: Cheng Wei Ming
 * @param  array $imgs          Picture Path Array
 * @param  array $info          An array of clipping information, including the width and height to be preserved after clipping, the ratio of image size to the starting coordinates of clipping
 * @param  bool $cover          Whether to overwrite the original image, default does not overwrite
 * @return array                If the number of clippings is returned by overwriting the original image, the array composed of the path of the returned image is not overwritten.
 */
function cut_img($imgs=array(),$infoarr=null,$cover=false)
{
    if($infoarr==null) return $imgs;

    //Determine whether it is an array (it must be an array of image paths)
    $imgs = is_array($imgs)?$imgs:array($imgs);

    //Cut multiple clipping information into an array of individual information
    $infoarr = explode(',', $infoarr);

    $save_file = array();

    $i=0;
    foreach($imgs as $file){

        //If you do not overwrite the original image, you can redefine the image save path
        if(false==$cover){
            $file = $file;
        }

        //Cut the clipping information into arrays. The first is the width to be preserved, the second is the height to be preserved, and the third and fourth are the ratio of the image width to the clipping starting point.
        $info = explode('#', $infoarr[$i]);

        //Cutting aspect ratio
        $ratio = $info[0]/$info[1];

        //Judging whether a picture exists
        if(!file_exists($file)) continue;

        //Getting Picture Information
        $imgize = getimagesize($file);

        //image width
        $width = $imgize[0];
        //Picture height
        $height = $imgize[1];

        //Starting point coordinates of image clipping
        $x = $info[2]==0?0:$imgize[0]/$info[2];
        $y = $info[3]==0?0:$imgize[1]/$info[3];

        //Judging the ratio of original width to height and the ratio of cut width to height
        if($width/$height>=$ratio){
            $width = $height*$ratio;//If it is larger than that, it is the cutting width.
        }else{
            $height = $width/$ratio;//Cutting height is less than
        }

        //The width of the clipping should not exceed the size of the picture
        if(($width+$x)>$imgize[0]){
            $width = $width-($width+$x-$imgize[0]);
        }

        if(($height+$y)>$imgize[1]){
            $height = $height-($height+$y-$imgize[1]);
        }

        //Create instances of source diagrams
        $src = imagecreatefromstring(file_get_contents($file));

        //Create an image
        $new_image = imagecreatetruecolor($info[0], $info[1]);

        //Assign colors
        $color = imagecolorallocate($new_image,255,255,255);
        //Defined as transparent color
        imagecolortransparent($new_image,$color);
        //Fill picture
        imagefill($new_image,0,0,$color);

        //Copy the picture and save it to the specified size
        imagecopyresized($new_image, $src, 0, 0, $x, $y, $info[0], $info[1], $width, $height);

        //Preservation

        if(false==$cover){
            $file = rtrim(dirname($file),'/').'/c_'.basename($file);
            $save_file[] = $file;
        }

        imagejpeg($new_image,$file);

        imagedestroy($new_image);
        imagedestroy($src);

        $i++;
    }

    if(false==$cover){
        return $save_file;
    }else{
        return $i;
    }
}

Posted by acroporas on Sat, 06 Apr 2019 17:54:31 -0700