This is an example of integrating ThinkPHP with jcrop Image Upload, cropping, and preview.

Source: Internet
Author: User
Tags crop image

It is often found that someone in the Technical Group asks for examples of uploading, cropping, and previewing PHP images. Today, we just had time to do this. At the same time, we published the method so that you can understand how to use ThinkPHP + jcrop for this example. First down jcrop, URL: http://deepliquid.com/content/Jcrop_Download.html

After the download is complete, there are examples in the js, demo, css and other folders. demo. We suggest you take a look at the source code first. The rest will be used with me for this example:

1. Download ThinkPHP, create a new project, and generate a project directory.

2. Create Index/index.html in Tpl

The Code is as follows:

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 


This is an upload task. After you click to upload an image, a window will pop up to upload the image for cropping. Create upimg.html under Tpl/Index/

The Code is as follows:

<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 


I didn't use the File Upload class that comes with TP. If you need it, you can change it. The above mainly shows a window for uploading files. In this window, file upload and cropping will be completed. Click Submit to Index/uploadf

The Index/uploadf code is as follows:

$ Path = "uploadfiles/"; // Image Upload address if (! File_exists ($ path) {mkdir ("$ path", 0700) ;}$ tp = array ("image/gif", "image/jpeg ", "image/png", "image/jpg"); if (! In_array ($ _ FILES ["filename"] ["type"], $ tp) {echo "format incorrect"; exit ();} // end if if ($ _ FILES ["filename"] ["name"]) {$ file1 = $ _ FILES ["filename"] ["name"]; $ file2 = $ path. time (). $ file1; $ flag = 1;} if ($ flag) $ result = move_uploaded_file ($ _ FILES ["filename"] ["tmp_name"], $ file2 ); if ($ result) {$ this-> assign ('filename', $ file2); $ this-> display ();}



After uploading is completed, the file will be directly uploaded to uploadf.html.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">



The code here is long. Let's explain it slowly. I copied the tutorial3.html in jcrop demoand loaded the js and css he needed. Where

#preview-pane .preview-container {    width: 170px;    height: 250px;    overflow: hidden;}


This part of CSS will affect the proportion of the cropping box. And the preview size.

$('#target').Jcrop({            onChange : updatePreview,            onSelect : updatePreview,            aspectRatio : xsize / ysize        }, function() {            var bounds = this.getBounds();            boundx = bounds[0];            boundy = bounds[1];            jcrop_api = this;            $preview.appendTo(jcrop_api.ui.holder);        });



OnChange and onSelect indicate the js code to be executed during cropping. To be honest, my js and jq levels are very junk. So it doesn't matter.

function updatePreview(c) {            if (parseInt(c.w) > 0) {                var rx = xsize / c.w;                var ry = ysize / c.h;                $pimg.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'                });                                                                                                                                                                                $('#x').val(c.x);                $('#y').val(c.y);                $('#w').val(c.w);                $('#h').val(c.h);            }        }        ;


I added a value assignment to the form. Then, the cropping is completed after submission to php.


Click Submit to uploadf to write an image cropping class first:

<? Phpclass Imgshot {private $ filename; private $ ext; private $ x; private $ y; private $ x1; private $ y1; private $ width = 170; private $ height = 250; private $ pai_quality = 90;/*** constructor */public function _ construct () {// log_message ('debug', "Img_shot Class Initialized ");} /***** initialize object ** @ param * filename the source file path is fully explicit * @ param * width * @ param * height * @ param * x abscissa 1 * @ param * y ordinate 1 *@ Param * x1 abscissa 1 * @ param * y1 abscissa 2 **/public function initialize ($ filename, $ x, $ y, $ x1, $ y1) {if (file_exists ($ filename) {$ this-> filename = $ filename; $ pathinfo = pathinfo ($ filename ); $ this-> ext = $ pathinfo ['extension'];} else {$ e = new Exception ('the file is not exists! ', 1050); throw $ e;} $ this-> x = $ x; $ this-> y = $ y; $ this-> x1 = $ x1; $ this-> y1 = $ y1;}/*** generate * different */public function generate_shot () {switch ($ this-> ext) based on the Image Format) {case 'jpg ': return $ this-> generate_jpg (); break; case 'png': return $ this-> generate_png (); break; case 'gif ': return $ this-> generate_gif (); break; default: return false ;}}/*** get the generated file name */private function get_shot_na Me () {$ pathinfo = pathinfo ($ this-> filename); $ fileinfo = explode ('. ', $ pathinfo ['basename']); $ filename = $ fileinfo [0]. '_ small. '. $ this-> ext; return 'uploadfiles /'. $ filename;}/*** generate a jpg image */private function generate_jpg () {$ shot_name = $ this-> get_shot_name (); $ img_r = imagecreatefromjpeg ($ this-> filename); $ dst_r = ImageCreateTrueColor ($ this-> width, $ this-> height); imagec Opyresampled ($ dst_r, $ img_r, 0, 0, $ this-> x, $ this-> y, $ this-> width, $ this-> height, $ this-> x1, $ this-> y1); imagejpeg ($ dst_r, $ shot_name, $ this-> 1__quality); return $ shot_name ;} /*** generate a gif image */private function generate_gif () {$ shot_name = $ this-> get_shot_name (); $ img_r = imagecreatefromgif ($ this-> filename ); $ dst_r = ImageCreateTrueColor ($ this-> width, $ this-> height); imagecopyr Esampled ($ dst_r, $ img_r, 0, 0, $ this-> x, $ this-> y, $ this-> width, $ this-> height, $ this-> x1, $ this-> y1); imagegif ($ dst_r, $ shot_name); return $ shot_name ;} /*** generate an image in png format */private function generate_png () {$ shot_name = $ this-> get_shot_name (); $ img_r = imagecreatefrompng ($ this-> filename ); $ dst_r = ImageCreateTrueColor ($ this-> width, $ this-> height); imagecopyresampled ($ dst_r, $ img_r, 0, 0, $ this-> x, $ this-> y, $ this-> width, $ this-> height, $ this-> x1, $ this-> y1); imagepng ($ dst_r, $ shot_name); return $ shot_name ;}}?>



This is my online down .~ You can expand it as needed.


Cropping operation:

$ Filename = $ this-> cut (); echo "<script language = 'javascript '>"; echo "alert (\" uploaded successfully! \ ");"; Echo "</script> "; echo ("<input type = \" button \ "name = \" Submit \ "value = \" OK \ "onClick = \" window. opener. setFile ('". $ filename. "'); window. close (); \ ">"); echo ''; // function cut () {import ('org. net. imgshot '); $ imgshot = new Imgshot (); $ imgshot-> initialize (SITE_PATH. '/'. $ _ REQUEST ['filename'], $ _ REQUEST ['X'], $ _ REQUEST ['y'], $ _ REQUEST ['X'] + $ _ REQUEST ['W'], $ _ REQUEST ['y'] + $ _ REQUEST ['H']); $ filename = $ imgshot-> generate_shot (); return $ filename ;}



After the cropping is completed, the final cropped image is directly echo and a confirmation button is displayed. Click OK, the address of the cropped image is returned to the initial input [type = "text"]. I have not completed the entire example. You can understand and improve it as needed. Well, if you don't know, you can join the group: 252799167 ask me. The entire example has been published on the ThinkPHP official website. You can download it.

Http://www.thinkphp.cn/topic/9154.html

This article is from the "Thunder" blog, please be sure to keep this source http://a3147972.blog.51cto.com/2366547/1336561

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.