search
HomeBackend DevelopmentPHP TutorialPHP 裁切有关问题,求大神指点指点,弄了一天了.

PHP 裁切问题,求大神指点指点,弄了一天了...
我前端用JCROP获取到x、y坐标、宽度、高度,传递到 uphoto.php处理,现在一切正常,但是如果前端用户选择的图片宽度过大(我用css样式控制用户选择的图片最大宽度为680px),裁切出来的就不正常了...我查阅了一些资料,说是需要按比例换算,但是是按什么比例换算啊,用户选择的图片的宽度(大于680px时)和680换算么?

这是 uphoto.php:

<br /><br /><br />$x1 = $_POST["x1"];<br />$x2 = $_POST["x2"];<br />$y1 = $_POST["y1"];<br />$y2 = $_POST["y2"];<br />$targ_w = $_POST["w"];<br />$targ_h = $_POST["h"];<br /><br /><br />if ($_FILES["mfile"]["error"]){echo "error: " . $_FILES["file"]["error"];}<br />if (!empty($_FILES["mfile"]["name"])){ //提取文件域内容名称,并判断<br />$path = "/upload/user/photo/"; //上传路径<br />//检查是否有该文件夹,如果没有就创建,并给予最高权限<br />//if(!file_exists($path)){mkdir("$path", 0700);}<br />//允许上传的文件格式<br />$allow_type = array("image/gif","image/pjpeg","image/jpeg","image/png");<br />//检查上传文件是否在允许上传的类型<br />if(!in_array($_FILES["mfile"]["type"], $allow_type)){echo "error:格式有误,仅支持gif/jpg/png"; exit();}<br />//检测图片大小<br />if($_FILES["mfile"]["size"] > 5*1024*1024){echo "error:文件不得超过5M"; exit();}<br />$filetype = $_FILES["mfile"]["type"];<br />if($filetype == "image/jpeg"){<br />$img_type = ".jpg";<br />}<br />if ($filetype == "image/jpg") {<br />$img_type = ".jpg";<br />}<br />if ($filetype == "image/pjpeg") {<br />$img_type = ".jpg";<br />}<br />if($filetype == "image/gif"){<br />$img_type = ".gif";<br />}<br />if($filetype == "image/png"){<br />$img_type = ".png";<br />}<br />if($_FILES["mfile"]["name"])<br />{<br />$randstr = random_str().date("YmdHis"); //获取时间并赋值给变量<br />$saveto = $_SERVER['DOCUMENT_ROOT'].$path.$randstr.$img_type; //图片的完整路径<br />$newimg = $randstr.$img_type; //图片名称<br />$flag=1;<br />}<br />//END IF<br />if ($flag){$result = move_uploaded_file($_FILES["mfile"]["tmp_name"], $saveto);}<br />//特别注意这里传递给move_uploaded_file的第一个参数为上传到服务器上的临时文件<br />$src_file = $saveto;<br />}}<br /><br /><br />$type = exif_imagetype($src_file);<br /><br />$support_type = array(IMAGETYPE_JPEG , IMAGETYPE_PNG , IMAGETYPE_GIF);<br />if(!in_array($type, $support_type, true)){echo "error:当前图片格式非JPG/PNG/GIF";exit();}<br />//Load image<br />switch($type) {<br />case IMAGETYPE_JPEG :<br />$src_img = imagecreatefromjpeg($src_file);<br />break;<br />case IMAGETYPE_PNG :<br />$src_img = imagecreatefrompng($src_file);<br />break;<br />case IMAGETYPE_GIF :<br />$src_img = imagecreatefromgif($src_file);<br />break;<br />default:<br />echo "Load image error!";<br />exit();<br />}<br /><br />$dst_r = ImageCreateTrueColor($targ_w, $targ_h);<br />list($width_orig, $height_orig) = getimagesize($src_file);<br />//if ($width_orig > 680){<br />//$new_width_orig = 680;<br />//$new_height_orig = ($height_orig*680)/$width_orig;<br />//}<br />//else {<br />//$new_width_orig = $targ_w;<br />//$new_height_orig = $targ_h;<br />//}<br /><br />//echo $new_width_orig."<br />";<br />//echo $new_height_orig."<br />";<br />//echo "x:".$x1."<br />";<br />//echo "y:".$y1;<br />//exit();<br /><br />imagecopyresampled($dst_r, $src_img, 0, 0, $x1, $y1, $targ_w, $targ_h, $targ_w, $targ_h);<br />//imagecopyresampled($dst_r, $src_img, 0, 0, $x1, $y1, $targ_w, $targ_h, $targ_w, $targ_h);<br /><br />switch($type) {<br />case IMAGETYPE_JPEG :<br />header('Content-type: image/jpeg');<br />imagejpeg($dst_r, null, 100);<br />break;<br />case IMAGETYPE_PNG :<br />header('Content-type: image/png');<br />imagepng($dst_r, null, 100);<br />break;<br />case IMAGETYPE_GIF :<br />header('Content-type: image/gif');<br />imagegif($dst_r, null, 100);<br />break;<br />default:<br />break;<br />}<br />echo "<img  src='". $dst_r ."' / alt="PHP 裁切有关问题,求大神指点指点,弄了一天了." >";<br />exit;<br /><br /><br />


求大神指点指点
------解决思路----------------------
用css样式控制用户选择的图片最大宽度为680px
就表示用户看到的是经过动态缩放的副本
那么你在传递裁剪区域坐标的时候,还需传递图片的原始尺寸
换算一下就可以了
X= x/680*图片宽


------解决思路----------------------
可以参考一下我之前写的裁剪。因为你是要裁剪,所以宽和高有一个是和裁剪后的尺寸的宽和高一样,另一边会>=裁剪后的。
http://blog.csdn.net/fdipzone/article/details/9316385

<br />    /** 获取目标图生成的size <br />    * @return Array $width, $height <br />    */  <br />    private function get_size(){  <br />        list($owidth, $oheight) = getimagesize($this->_source);  <br />        $width = (int)($this->_width);  <br />        $height = (int)($this->_height);  <br />          <br />        switch($this->_type){  <br />            case 'fit':  <br />                $pic_w = $width;  <br />                $pic_h = (int)($pic_w*$oheight/$owidth);  <br />                if($pic_h>$height){  <br />                    $pic_h = $height;  <br />                    $pic_w = (int)($pic_h*$owidth/$oheight);  <br />                }  <br />                break;  <br />            case 'crop':  <br />                $pic_w = $width;  <br />                $pic_h = (int)($pic_w*$oheight/$owidth);  <br />                if($pic_h<$height){  <br />                    $pic_h = $height;  <br />                    $pic_w = (int)($pic_h*$owidth/$oheight);  <br />                }  <br />                break;  <br />        }  <br />  <br />        return array($pic_w, $pic_h);  <br />    } <br />

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool