Cropping pictures is very familiar to us. I have encountered this need again at work recently, so I thought I would simply sort it out. The method can be referenced by everyone and myself when needed, so this article mainly introduces it. In order to use Javascript to crop pictures and store them in a simple way, I use the THINKPHP framework for back-end PHP processing. Friends in need can refer to it.
Preface
As far as I am concerned, there are not many parts of the page that are more flexible in design, such as sliding verification codes and image cropping. Waiting for better interaction design.
When I first started working, I wanted to understand these things, but I never had the need. I took advantage of my free time today and studied it all afternoon. During this period, I encountered problems of all sizes, and I have been preparing for them. Being tortured actually reflects a problem. My
is still relatively weak.
Achievement effect:
After the user clicks to upload the image, the page displays the uploaded image, and a cropping box and two preview areas appear. Finally, click the crop button to save the cropped image to the server.
The effect is very simple. There are two difficulties I encountered in the whole process. The first is the JS effect of cropping, and the second is the processing of image data.
For the first question, I quoted a plug-in on the Internet. As far as I feel, the user satisfaction in the cropping process can only be considered average, because it can only crop square areas. , even though there are eight pull settings on the border, the frame still scales according to the square when pulling the frame, which is not very satisfactory to me.
The implementation method is as follows:
The following is a simple page design:
<p style="float:left;"><img src="/static/imghwm/default1.png" data-src="/plug/js/jquery.min.js" class="lazy" id="target" alt="Simple sample code to crop and store images using Javascript" ></p> <p style="width:48px;height:48px;margin:10px;overflow:hidden; float:left;"><img src="/static/imghwm/default1.png" data-src="/plug/js/jquery.min.js" class="lazy" style="max-width:90%" id="preview" alt="Simple sample code to crop and store images using Javascript" ></p> <p style="width:190px;height:195px;margin:10px;overflow:hidden; float:left;"><img src="/static/imghwm/default1.png" data-src="/plug/js/jquery.min.js" class="lazy" style="max-width:90%" id="preview2" alt="Simple sample code to crop and store images using Javascript" ></p> <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="裁剪"/> </form>
The following is 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"}); // 限制了大小会影响到截图的效果 }; 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; //小头像预览p的大小 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; //大头像预览p的大小 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:
One: Don’t forget to put it in the header of the page Introducing plug-ins:
<script 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" />
Second: Some people with sharp eyes may have seen a timing in JS, and at the same time they are confused, isn't this a bit unnecessary? Actually no, it takes time to upload the image to JS and load it on the page. The meaning of this timing is to wait until the image is loaded on the page by JS before loading the cropping effect. This is also obtained after repeated experiments. way of doing.
I use the THINKPHP framework for back-end PHP processing, the version is 3.1.3Paste 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']); //缩放 // imagecopyresampled($cropped_img,$srcImg,0,0,$_POST['x'],$_POST['y'],$_POST['w'],$_POST['h'],$width,$height); //裁剪 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); } }
Here is the call to the GD library There are a series of methods to create images, the most important one is
imagecopy(), which copies the original image to a new image according to the specified cropping position and cropping size. This also explains one thing, the page When the user cuts the image , the front end does not actually operate on the image. Instead, it obtains the coordinate position when cropping, the cropping size, and then submits it to PHP for operation! !
Summarize
The above is the detailed content of Simple sample code to crop and store images using Javascript. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
