Simple implementation of cutting pictures and storing them by Javascript

  • 2021-08-03 08:49:41
  • OfStack

Preface

As far as I am concerned, there are not many smart parts of the design on the page, such as sliding verification code, picture cropping and other better interactive designs.

From the beginning of work, I want to understand these things, but I didn't have this demand. I took advantage of today's free time and studied it for one afternoon. During the period, I encountered large and small problems, and I was tortured. This actually reflects one problem, my

Still relatively weak.

Realization effect:

After the user clicks Upload Picture, the page displays the uploaded picture, and a cropping box and two preview areas appear. Finally, click the cropping button to save the cropped picture to the server.

The effect is very simple. I encountered two difficulties in the whole process. The first one is the cropped JS effect, and the second one is the processing of picture data.

For the first question, I quoted a plug-in on the Internet. As far as I feel, the satisfaction of users in the clipping process can only be counted as 1, because it can only clip square areas. Even if there are 8 pull settings on the border, the pull box is still scaled by square, which is not very satisfactory to me.

The implementation method is as follows:

Here's a simple page design:


<div style="float:left;"><img id="target"></div>
<div style="width:48px;height:48px;margin:10px;overflow:hidden; float:left;"><img style="float:left;" id="preview" ></div>
<div style="width:190px;height:195px;margin:10px;overflow:hidden; float:left;"><img style="float:left;" id="preview2" ></div>
<form action="{:U('/test/crop_deal')}" method="post" onsubmit="return checkCoords()" enctype="multipart/form-data" id="form">
<input type="file" name="file" onchange="change_image(this)">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="submit" value=" Cutting "/>
</form>

Here's the JS code:


function change_image(file){
var reader = new FileReader();
reader.onload = function(evt){
$("#target").attr('src',evt.target.result);
$('#preview').attr('src',evt.target.result);
$('#preview2').attr('src',evt.target.result);
// $('#target').css({"height":"600px","width":"600px"});
//  Limiting the size will affect the effect of screenshots 
};
reader.readAsDataURL(file.files[0]);

var jcrop_api, boundx, boundy;

setTimeout(function(){


$('#target').Jcrop({
minSize: [48,48],
setSelect: [0,0,190,190],
onChange: updatePreview,
onSelect: updatePreview,
onSelect: updateCoords,
aspectRatio: 1
},
function(){
// Use the API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the API in the jcrop_api variable
jcrop_api = this;
});

function updatePreview(c){
if (parseInt(c.w) > 0)
{
var rx = 48 / c.w; // Small head preview Div The size of 
var ry = 48 / c.h;

$('#preview').css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
{
var rx = 199 / c.w; // Big Head Preview Div The size of 
var ry = 199 / c.h;
$('#preview2').css({
width: Math.round(rx * boundx) + 'px',
height: Math.round(ry * boundy) + 'px',
marginLeft: '-' + Math.round(rx * c.x) + 'px',
marginTop: '-' + Math.round(ry * c.y) + 'px'
});
}
};


function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};

},500);

}

Here are two reminders:

Its 1: Don't forget to introduce plug-ins at the head of the page:


    <script src="/plug/js/jquery.min.js" type="text/javascript"></script>
    <script src="/plug/js/jquery.Jcrop.min.js" type="text/javascript"></script>
    <link rel="stylesheet" href="/plug/css/Jcrop.css" rel="external nofollow" type="text/css" />

Its 2: If some people are sharp-eyed, they may see that there is a timing in JS. At the same time, are they psychologically puzzled that this is not a bit more than this one move? Actually, it takes time to upload pictures to JS and load them on the page. The significance of this timing lies in

Wait until the picture is loaded on the page by JS to load the clipping effect, which is also the practice obtained after repeated experiments.

I used the THINKPHP framework for back-end PHP processing, version 3.1. 3

Stick the code:


function crop_deal(){
    ob_clean();
    import ( 'ORG.Net.UploadFile' );
    $upload = new UploadFile ();
    $upload->maxSize = 2000000;
    $upload->allowExts = array (
          'jpg',
          'gif',
          'png',
          'jpeg'
    );
    $upload->savePath = './upload/test/';
    $upload->autoSub = true;
    $upload->subType = 'date';
    $upload->dateFormat = 'Ymd';
    if ($upload->upload () ) {
          $info = $upload->getUploadFileInfo();
          $new_path = "./upload/test/thumb".date('Ymd');
          $file_store = $new_path."/".date('YmdHis').".jpg";
          if(!file_exists($new_path)){
                mkdir($new_path,0777,true);
          }
          $source_path = "http://".$_SERVER['HTTP_HOST']."/upload/test/".$info[0]['savename'];
          $img_size = getimagesize($source_path);
          $width = $img_size[0];
          $height = $img_size[1];    
          $mime = $img_size['mime'];
          $srcImg = imagecreatefromstring(file_get_contents($source_path));
          $cropped_img = imagecreatetruecolor($_POST['w'], $_POST['h']);
          // Zoom 
          // imagecopyresampled($cropped_img,$srcImg,0,0,$_POST['x'],$_POST['y'],$_POST['w'],$_POST['h'],$width,$height);
          // Cutting 
          imagecopy($cropped_img,$srcImg,0,0,$_POST['x'],$_POST['y'],$_POST['w'],$_POST['h']);
          header("Content-Type:image/jpeg");
          imagejpeg($cropped_img,$file_store);
          imagedestroy($srcImg);
          imagedestroy($cropped_img);
    }

}

This is a series of methods to call GD library to create images, and the most important thing is imagecopy() It is to copy the original image to the new image according to the specified cropping position and cropping size, which also shows one thing, the page user is cropping the image

In fact, the front end does not operate on the picture, but gets the coordinate position and clipping size when clipping, and then submits it to PHP operation! !

Summarize


Related articles: