KodeInfo | Learning resources for web and mobile development

Cropping Images Using Jcrop In PHP

September 22nd, 2014 10:40:53 in PHP Beginners , PHP Intermediate by Irfan Iqbal Comments(0) - Views(7474)
Tags : cropping images in php, php image crop, using jcrop librabry, crop image in php

In this post let us study how to crop images with Jquery and PHP using jcrop javascript library.At first you nees to download a jcrop javacript library from http://deepliquid.com/content/Jcrop_Download.html .

After downloading copy the jcrop.js file into your root folder .

Now let us Create a HTML File to display the image.

<!DOCTYPE html>
<head>
	<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
	<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
	<script src="/posts/jcrop/js/jquery.Jcrop.js"></script>

	<script type="text/javascript">
		$(function() {
			$('#cropbox').Jcrop({
				aspectRatio : 1,
				onSelect : updateCoords
			});
		});

		function updateCoords(c) {
			$('#x').val(c.x);
			$('#y').val(c.y);
			$('#w').val(c.w);
			$('#h').val(c.h);
		};

		function checkCoords() {
			if (parseInt($('#w').val()))
				return true;
			alert('Please select a crop region then press submit.');
			return false;
		};
	</script>
</head>

<body>

	<img src="1.jpg" id="cropbox" />
	<form action="imagecrop.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" class="btn btn-large btn-inverse" />
	</form>          </p>

</body>

</html>

In the above code we are taking coordinates for cropping the image now let us create a PHP file .

<?php

if ($_POST) {
	$targ_w = $targ_h = 150;
	$jpeg_quality = 90;

	$src = '1.jpg';//imagesource
	$img_r = imagecreatefromjpeg($src);
	$dst_r = ImageCreateTrueColor($targ_w, $targ_h);

	imagecopyresampled($dst_r, $img_r, 0, 0, $_POST['x'], $_POST['y'], $targ_w, $targ_h, $_POST['w'], $_POST['h']);

	header('Content-type: image/jpeg');
	imagejpeg($dst_r, null, $jpeg_quality);
}
?>

Thanks switch to another posts for more .

Author

  • Irfan Iqbal
    Irfan Iqbal

    Irfan is a web developer and consultant from India. He is the co-founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, manages everything related to marketing and seo for kodeinfo , works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Related

WHY USE A FRAMEWORK OVER PLAIN PHP

WHY USE A FRAMEWORK OVER PLAIN PHP
read more

GETTING STARTED WITH LARAVEL

GETTING STARTED WITH LARAVEL
read more

UNDERSTANDING LARAVEL STRUCTURE

UNDERSTANDING LARAVEL STRUCTURE
read more

UNDERSTANDING LARAVEL ROUTES

UNDERSTANDING LARAVEL ROUTES
read more

comments powered by Disqus