search
HomeBackend DevelopmentPHP Tutorial 利用jquery Jcrop跟 php实现截图功能

利用jquery Jcrop和 php实现截图功能

项目中用到了一个上传头像的功能,需要进行无刷新的图片上传,并对上传后的图片进行用户要求的截图,无刷新上传我就不说了,用的Juploader,相信大家并不陌生,重点讲一下jcron和php配置实现图片的截取的功能,好了,言归正传。首先介绍一下jcron的用法,我就不一一解释了,我们只看最经常用的到截图功能:

<span style="font-size: 18px; ">$(function(){


				$('#cropbox').Jcrop({
					aspectRatio: 1,
					onSelect: updateCoords
				});


			});</span>

以上是控制,对哪个图片进行截图,“cropbox”是你要截取的img对象的id,“aspectRatio”控制等比例截取,“onSelect”的值是一个方法名,在选取时调用的方法

,个参数详情解释如下:

Option Name Value Type Description Default
aspectRatio decimal Aspect ratio of w/h (e.g. 1 for square) n/a
minSize array [ w, h ] Minimum width/height, use 0 for unbounded dimension n/a
maxSize array [ w, h ] Maximum width/height, use 0 for unbounded dimension n/a
setSelect array [ x, y, x2, y2 ] Set an initial selection area n/a
bgColor color value Set color of background container 'black'
bgOpacity decimal 0 - 1 Opacity of outer image when cropping .6
选取时的回调方法
<span style="font-size:18px;">function updateCoords(c)
			{
				$('#x').val(c.x);
				$('#y').val(c.y);
				$('#w').val(c.w);
				$('#h').val(c.h);
			};</span>

有了这个方法,可以在你截图是更新隐藏域中的坐标值,通过隐藏域把坐标信息传到后台。

<span style="font-size:18px;"><form action="crop.php" method="post" onsubmit="return checkCoords();">
			<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="Crop Image">
		</form></span>

ok,到此,前台已经告一段落,我们看后台的php代码。

后台php主要是根据前台传递的坐标,对原图进行截取,支持jpg,png,和gif三种图片格式,当然,你可以扩展他,使他支持更多的图片格式。

<span style="font-size:18px;">class Img_shot
{
	
	private $filename;
	private $ext;
	private $x;
	private $y;
	private $x1;
	private $y1;
	private $width = 124;
	private $height = 124;
	private $jpeg_quality = 90;
	/**
	 * 构造器
	 *
	 * 
	 */
	public function __construct()
	{
		log_message('debug', "Img_shot Class Initialized");
	}
	/**
	 * 初始化截图对象
	 *@param filename 源文件路径全明
	 *@param width  截图的宽
	 *@param height  截图的高
	 *@param x  横坐标1
	 *@param y  纵坐标1
	 *@param x1  横坐标1
	 *@param y1  横坐标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;	
	}
	/**
	 * 生成截图
	 * 根据图片的格式,生成不同的截图
	 */
	public function generate_shot()
	{
		switch($this->ext)
		{
			case 'jpg':
				return $this->generate_jpg();
				break;
			case 'png':
				return $this->generate_png();
				break;
			case 'gif':
				return $this->generate_gif();
				break;
			default:
				return false;
		}
	}
	/**
	 * 得到生成的截图的文件名
	 * 
	 */
	private function get_shot_name()
	{
		$pathinfo = pathinfo($this->filename);
		$fileinfo = explode('.',$pathinfo['basename']);
		$filename = $fileinfo[0] . '_small.' . $this->ext;
		return $pathinfo['dirname'] . '/' .$filename;
	}
	/**
	 * 生成jpg格式的图片
	 * 
	 */
	private function generate_jpg()
	{
		$shot_name = $this->get_shot_name();
		$img_r = imagecreatefromjpeg($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);
		imagejpeg($dst_r,$shot_name,$this->jpeg_quality);
		return $shot_name;
	}
	/**
	 * 生成gif格式的图片
	 * 
	 */
	private function generate_gif()
	{
		$shot_name = $this->get_shot_name();
		$img_r = imagecreatefromgif($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);
		imagegif($dst_r,$shot_name);
		return $shot_name;
	}
	/**
	 * 生成png格式的图片
	 * 
	 */
	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;
	}
}		</span>

接收到前台的坐标信息后,你可以实例化该类,用来生成图片,返回生成的图片的名称,你就可以使用啦。


截完图之后:


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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools