返回列表 發帖

[jQuery] Jcrop - 影像框選、切圖介面

Jcrop
http://deepliquid.com/content/Jcrop.html
影像框選、切圖介面

使用方式

下載 jQuery Jcrop 後,將 js 和 css 引用進來。
<link rel="stylesheet" type="text/css" href="jquery.Jcrop.css" />  
<script type="text/javascript" src="jquery-1.3.1-min.js"></script>
<script type="text/javascript" src="jquery.Jcrop.min.js"></script>

基本的範例

就如同其他 jQuery 的 plugin 一樣,使用上非常容易。首先將要加入切圖介面的圖檔加上特定的 id
<img src="P1010536.JPG" id="jcrop_target" />
接著透過 jQuery 將這個元素選起來後,套用 Jcrop() 即可
$('#jcrop_target').Jcrop();
以下是套用 Jcrop() 後的範例,可以直接在圖片上拖曳進行範圍的框選



取得選取範圍

當然只有切圖的框選介面是不夠的,至少還要能得到選取的範圍才行。這時可以透過 Jcrop 本身提供的 callback 功能,當選取區塊有變動時,呼叫 callback 函數並處理選取的值。

callback 函數這樣寫:
function showCoords(c) {
  //這邊取得的 c 就是座標相關資料,包含:
  //c.x  --> 左上角的 x
  //c.y  --> 左上角的 y
  //c.x2 --> 右下角的 x
  //c.y2 --> 右下角的 y
  //c.w  --> 選取範圍的寬度
  //c.h  --> 選取範圍的高度
};
套用 Jcrop 時改帶入一個參數,指定這個 callback 的函數
$('#jcrop_target2').Jcrop({
  onChange: showCoords,
  onSelect: showCoords
});
以下是取得框選範圍的範例:




後端切圖

實際應用時,你可以先把這些框選的值存入一個 hidden 的欄位後,待使用者 submit 後,再透過後端的程式去執行切圖的作業。

後端則看你使用什麼程式去做,以 PHP 來說,可以透過 gd 的函數去切圖,官方網站有個簡單的範例可參考:
http://deepliquid.com/content/Jcrop_Implementation_Theory.html

這個是直接將圖輸出的範例:
<?php

$targ_w = $targ_h = 150;
$jpeg_quality = 90;

$src = 'demo_files/flowers.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);

?>
如果要把圖存檔,可以修改為下面這段:
// 把這一行 remark 起來
// header('Content-type: image/jpeg');

imagejpeg($dst_r, $output_filename, $jpeg_quality); //存檔,記得給正確的檔名
To infinity and beyond!

返回列表 回復 發帖