Php+croppic.js Implement cut upload image

Source: Internet
Author: User
Tags crop image transparent color rotate image

Recently need to implement crop image upload, think of a previous company used a plug-in, but do not know what name.

Looked for some time on the net, finally found this website.

http://www.croppic.net/

Because the official website documents are all in English, so it looks a bit difficult, can probably read 80%, but the lack of detailed case description, so the real configuration is still very confused force.

If you follow the steps of the official website, this is probably the case.

Download installation

There are two kinds of download methods, the first one is similar to the SDK whole website, the other is a concise version of the croppic. The former provides a complete project structure and a front-end case, the latter only croppic.css, Croppic.js, croppic.min.js three files.

Basic use

CSS Section
#yourId {
width:200px;
height:150px;
position:relative; /* or fixed or absolute */
}

HTML section
<div id= "Yourid" ></div>

JS section
var options = [
Uploadurl: ' Image upload address ',
Cropurl: ' The address sent after the picture is cut ',
And so on. Various parameter configuration information
];
var cropperheader = new Croppic (' Yourid ', options);

Options parameter Uploadurl
Uploadurl: ' Make upload address ', uploaddata:{' dummydata ': 1, ' dummyData2 ': ' Text '}

PHP processing, and ordinary upload files exactly the same, using $_files[' img '] can directly obtain the file information, upload and save, using $_request[] directly can get the data in JS Uploaddata.
After processing is completed, PHP returns the following JSON structure based on the success status
    • When successful
"Status": "Success",     "url": "Return successful image URL address",     "width": source Picture width
   "Height": Source Image Height
}

Note: The source image is wide-height get the list ($width, $height) = getimagesize ($_files["img" ["Tmp_name"]);

    • When failed
{    "status": "Error",    "message": "Here is your failure message"}  
Cropurl

Next is the request to crop the picture, basic use

var cropperoptions = {      uploadurl:' requested address after cut ',      uploaddata:{            ' dummydata ': 1 ,            " DummyData2 ":" Text "      }}varnew croppic (' Yourid ', cropperoptions);

The parameters to request PHP are basically as follows:

The PHP side uses Nezamy/route's request class to get the parameters that are sent after the croppic.js is cut.

$request= App (' request ');//image path of the upload server$IMGURL=$request->body[' Imgurl '];//Original picture Width height$imgInitW=$request->body[' IMGINITW '];$imgInitH=$request->body[' Imginith '];//new scaled picture width height$imgW=$request->body[' IMGW '];$imgH=$request->body[' IMGH '];//The upper-left corner of the cropped image associated with the scaled image$imgY 1=$request->body[' imgY1 '];$imgX 1=$request->body[' imgX1 '];//crop image Width Height$cropW=$request->body[' CROPW '];$cropH=$request->body[' Croph '];//Angle$angle=$request->body[' rotation '];

Other parameters will not be introduced, the document can be seen above, if you do not understand or not too clear can directly download the case for reference, than the document to be more detailed. The next plays are handled on the PHP side.

PHP various operation Pictures GD library
$temp _name= "Crop_temp_".uniqid();$temp _path= Sys_get_temp_dir (). "/";$output _filename=$temp _path.$temp _name;$what=getimagesize($IMGURL);//Create a canvas and load imagesSwitch(Strtolower($what[' MIME '])) {     Case' Image/png ':$source _image= Imagecreatefrompng ($IMGURL); $type= '. png ';  Break;  Case' Image/jpeg ':$source _image= Imagecreatefromjpeg ($IMGURL); $type= '. jpeg ';  Break;  Case' Image/gif ':$source _image= Imagecreatefromgif ($IMGURL); $type= '. gif ';  Break; default:Throw New\Exception(' Unsupported picture type ');}if(!is_writable(dirname($output _filename))) {    Throw New\Exception(' file cannot be written ');}//Create a true color image to support richer colors, GIF files are not available$resizedImage= Imagecreatetruecolor ($imgW,$imgH);if($type= = '. png ') {    //define black as a transparent colorImagecolortransparent ($resizedImage, Imagecolorallocate ($resizedImage, 0, 0, 0));} Imagecopyresampled ($resizedImage,$source _image, 0, 0, 0, 0,$imgW,$imgH,$imgInitW,$imgInitH);//Rotate Image$rotated _image=$angle? Imagerotate ($resizedImage, -$angle, 0):$resizedImage;//Get image Width height$rotated _width= Imagesx ($rotated _image);$rotated _height= Imagesy ($rotated _image);//after rotation-after zooming$DX=$rotated _width-$imgW;$dy=$rotated _height-$imgH;//crop a rotated picture to an image$cropped _rotated_image= Imagecreatetruecolor ($imgW,$imgH);if($type= = '. png ') {    //set Black to transparentImagecolortransparent ($cropped _rotated_image, Imagecolorallocate ($cropped _rotated_image, 0, 0, 0));} Imagecopyresampled ($cropped _rotated_image,$rotated _image, 0, 0,$DX/2,$dy/2,$imgW,$imgH,$imgW,$imgH);//cut the image to the specified area$final _image= Imagecreatetruecolor ($cropW,$cropH);if($type= = '. png ') {imagecolortransparent ($final _image, Imagecolorallocate ($final _image, 0, 0, 0));} Imagecopyresampled ($final _image,$cropped _rotated_image, 0, 0,$imgX 1,$imgY 1,$cropW,$cropH,$cropW,$cropH);//The final output image to the file, you can directly use File_get_content (' Output_filename '. $type) to get the picture.Imagepng ($final _image,$output _filename.$type);

/**
* Upload Server operation is required here
*/

Echo Json_encode ([
' Status ' = ' success ',
' url ' = $output _filename. $type,
]);
Finally delete the cached picture
Unlink ($output _filename. $type);
JS various configurations
varCROP_IMAGE_SRC = ' image_src '; varCroppedoptions ={cropurl:' Http://deng.com/m/tool/crop_pic/crop ', modal:true, Doublezoomcontrols:false, Enablemousescroll:true, imgeyecandyopacity:0.4, Rotatefactor:90, Zoomfactor:20, Outputurlid:' Image_input ',        //loadpicture: ' Download the picture ',Processinline:true, loaderhtml:' <div class= "loader bubblingg" ><span id= "bubblingg_1" ></span><span id= "BubblingG_2" ></ Span><span id= "Bubblingg_3" ></span></div> ', Onbeforeimgupload:function() {crop_image_src= $ (' #image_input '). Val (); }, Onafterremovecroppedimg:function () {            varres = confirm (' Do you want to use the original image or clear the picture? \n\r[confirm] Use original image, [Cancel] erase picture '); if(RES) {$ (' #image_input '). Val (CROP_IMAGE_SRC); $(' #cropContainerEyecandy '). Prepend ('  '); } Else {                $(' #image_input '). Val ('); $('. Croppedimg '). Remove (); }}, OnReset:function () {            varres = confirm (' Do you want to use the original image or clear the picture? \n\r[confirm] Use original image, [Cancel] erase picture '); if(RES) {$ (' #image_input '). Val (CROP_IMAGE_SRC); $(' #cropContainerEyecandy '). Prepend ('  '); } Else {                $(' #image_input '). Val ('); }}, OnError:function(errormessage) {alert (' OnError: ' +errormessage)}    }; varCropperbox =NewCroppic (' Cropcontainereyecandy ', croppedoptions);

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.