php – jquery – 裁切圖片

使用jquery imgAreaSelect選取要裁切的範圍
網址:http://odyniec.net/projects/imgareaselect/

並且可以設定最大範圍與最小範圍或是不限制範圍~~
以下是範例,我寫在同一張PHP,實做的時候建議分開來吧!

<?
if (isset($_POST['submit']))
{
	//裁切圖片
	function cutimg($fromimgname, $fromimg_startx, $fromimg_starty, $newimg_width, $newimg_height)
	{
		//取得目標檔案的長寬
		$fromimg = imagecreatefromjpeg($fromimgname);
		$fromimg_info = getimagesize($fromimgname);
		$fromimg_width = $fromimg_info[0];
		$fromimg_height = $fromimg_info[1];

		//新檔案的寬高
		$newimg = imagecreatetruecolor($newimg_width, $newimg_height); // 超過256色改用這個

		//進行裁切
		imagecopy($newimg, $fromimg, 0,0,$fromimg_startx,$fromimg_starty,$newimg_width,$newimg_height);

		return $newimg;
	}

	$newimg = cutimg($_POST['imgfile'], $_POST['x1'], $_POST['y1'], $_POST['width'], $_POST['height']);
	header("Content-Type: image/jpg");
	mb_http_output("pass");
	imagejpeg($newimg); //直接顯示來TEST, 增加第2個參數可以存成圖片

	die;
}
?>
<link rel="stylesheet" type="text/css" href="jquery.imgareaselect-0.9.10/css/imgareaselect-default.css" />
<script type="text/javascript" src="jquery.imgareaselect-0.9.10/scripts/jquery.min.js"></script>
<script type="text/javascript" src="jquery.imgareaselect-0.9.10/scripts/jquery.imgareaselect.pack.js"></script>

<script>
$(function (){

    $('img#photo').imgAreaSelect({
        handles: true,
		aspectRatio : "4:3", //比例
		fadeSpeed : 200,
		maxWidth : 200,
		maxHeight : 200,
		minWidth : 100,
		minHeight: 100,
		outerOpacity : 0.9, //指定透明度
        onSelectChange: function (img, selection){

			//x1, y1 為左上角座標
			//x2, y2 為右下表座標

			$("[name=x1]").val(selection.x1)
			$("[name=y1]").val(selection.y1)
			$("[name=x2]").val(selection.x2)
			$("[name=y2]").val(selection.y2)
			$("[name=width]").val(selection.width)
			$("[name=height]").val(selection.height)
			}

		});

	})
</script>
<img id="photo" src="Koala.jpg">

<form action="" method="post" enctype="multipart/form-data">
    <input type="hidden" name="x1" value="" />
    <input type="hidden" name="y1" value="" />
    <input type="hidden" name="x2" value="" />
    <input type="hidden" name="y2" value="" />
    <input type="hidden" name="width" value="">
    <input type="hidden" name="height" value="">
    <input type="hidden" name="imgfile" value="Koala.jpg">
    <input type="submit" name="submit" value="Submit" />
</form>

發表迴響