Jcrop是一個(gè)非常棒的圖片裁剪JQuery插件,用鼠標(biāo)在圖片上自由拖動(dòng),就可以完成圖片的裁剪。
Demo地址:http://deepliquid.com/projects/Jcrop/demos.php?demo=live_crop
下面就來(lái)實(shí)現(xiàn)這個(gè)Demo的代碼:
注意:圖片地址為紅色,兩處都要修改。
效果圖:
HTML頁(yè)面部分:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Jcrop實(shí)現(xiàn)圖片裁剪 - 西部e網(wǎng)(weste.net)</title>
<script src="../styles/jquery-1.7.2.min.js"></script>
<script src="../styles/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="../styles/jquery.Jcrop.min.css" type="text/css" />
<style type="text/css">
#preview{width:100px;height:100px;border:1px solid #000;overflow:hidden;}
#imghead{filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image);}
</style>
<script language="Javascript">
jQuery(function(){
jQuery('#imghead').Jcrop({
aspectRatio: 1,
onSelect: updateCoords, //當(dāng)選中區(qū)域的時(shí)候,執(zhí)行對(duì)應(yīng)的回調(diào)函數(shù)
onChange: updateCoords, //當(dāng)選擇區(qū)域變化的時(shí)候,執(zhí)行對(duì)應(yīng)的回調(diào)函數(shù)
});
});
function updateCoords(c)
{
jQuery('#x').val(c.x); //得到選中區(qū)域左上角橫
jQuery('#y').val(c.y); //得到選中區(qū)域左上角縱坐標(biāo)
//jQuery("#x2").val(c.x2); //得到選中區(qū)域右下角橫坐標(biāo)
//jQuery("#y2").val(c.y2); //得到選中區(qū)域右下角縱坐標(biāo)
jQuery('#w').val(c.w); //得到選中區(qū)域的寬度
jQuery('#h').val(c.h); //得到選中區(qū)域的高度
};
function checkCoords()
{
if (parseInt(jQuery('#w').val())>0) return true;
alert('請(qǐng)選擇區(qū)域再提交.');
return false;
};
</script>
</head>
<body>
<img id="imghead" border=0 src='../image/b4.jpg' />
<form action="crop.php" method="post" onsubmit="return checkCoords();">
<input type="text" id="x" name="x" />
<input type="text" id="y" name="y" />
<input type="text" id="w" name="w" />
<input type="text" id="h" name="h" />
<input type="submit" value="提交">
</form>
</body>
</html>
PHP文件代碼(crop.php):
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$targ_w = $targ_h = 150;
$jpeg_quality = 90;
$src = '../image/b4.jpg';
$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);
exit;
}
?>