這個外掛讓使用者在瀏覽器裡拖曳、縮放並框選出要保留的區域,再把座標交給後端實際裁切。前端只負責互動與回報參數,真正的像素處理在伺服器端完成。
ui.draggable.js 是必須的(拖曳與縮放都靠它)。src 屬性的 img 標籤上,外掛在初始化時就會檢查,否則直接丟出例外。
var imageCropper = $('#imgBackground').imageCropper();
外掛會把原圖路徑、縮放比例與裁切框的座標寫進 settings,前端只要組進查詢字串即可:
$('#imgCroppedImage').attr('src',
'CropImage.ashx?p=' + imageCropper.settings.imagePath +
'&z=' + imageCropper.settings.zoomLevel +
'&t=' + imageCropper.settings.top +
'&l=' + imageCropper.settings.left +
'&w=' + imageCropper.settings.width +
'&h=' + imageCropper.settings.height +
'&' + Math.random());
加上的 Math.random() 是為了避開瀏覽器快取,確保每次都真的重新裁切。
public class CropImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string imgPath = Convert.ToString(context.Request["p"]);
float zoomLevel = Convert.ToSingle(context.Request["z"]);
int top = Convert.ToInt32(context.Request["t"]);
int left = Convert.ToInt32(context.Request["l"]);
int width = Convert.ToInt32(context.Request["w"]);
int height = Convert.ToInt32(context.Request["h"]);
context.Response.ContentType = "image/jpeg";
Crop(HttpContext.Current.Server.MapPath(imgPath),
zoomLevel, top, left, width, height)
.WriteTo(context.Response.OutputStream);
}
public MemoryStream Crop(string imgPath, float zoomLevel,
int top, int left, int width, int height)
{
Image img = Image.FromFile(imgPath);
Bitmap bitmap = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bitmap);
// 因為使用者看到的圖是縮放後的,所以要除以 zoomLevel 還原為原圖座標
g.DrawImage(img,
new Rectangle(0, 0, width, height),
new Rectangle((int)(left / zoomLevel), (int)(top / zoomLevel),
(int)(width / zoomLevel), (int)(height / zoomLevel)),
GraphicsUnit.Pixel);
MemoryStream ms = new MemoryStream();
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
img.Dispose();
g.Dispose();
bitmap.Dispose();
return ms;
}
public bool IsReusable { get { return false; } }
}
/**
* Copyright (c) 2010 Viewercq
* Dual licensed under the MIT and GPL licenses.
* Version: 1.0
*/
; (function($) {
$.fn.extend({
imageCropper: function(options) {
if (!this.is('img') || typeof this.attr('src') == 'undefined' || this.attr('src') == '') {
throw 'Please notice that this jquery plguin only could be applied to img and the src of img could not be null!';
}
var defaults = {
imagePath: this.attr('src'), // 原圖路徑
zoomLevel: 1, // 縮放級別
center: false, // 圖片相對於截取框是否居中
left: 0, top: 0, // 截取框與圖片的相對位置
width: 200, height: 200, // 截取框大小
cropWorkAreaSize: { width: 600, height: 400 }, // 工作區大小
cropFrameRect: { center: true, top: 0, left: 0 }, // 截取框相對於工作區的位置
zoom: { min: 0, max: 2, step: 0.01 }, // 縮放範圍
callbacks: {
dragging: false, // 移動圖片後
zoomed: false // 縮放後
}
};
if (options) { defaults = $.extend(defaults, options); }
return new imageCropper(this, defaults);
}
});
function imageCropper(image, settings) {
this.init(image, settings);
}
imageCropper.prototype = {
settings: false,
wrapper: $('<div class="image-cropper-wrapper"/>'),
zoomWrapper: $('<div class="zoom-wrapper"><div class="zoom-out-button"/><div class="zoom-scrollbar"><div class="zoom-scroller"/></div><div class="zoom-in-button"/></div>'),
img: false,
init: function(image, settings) {
var context = this;
this.settings = settings;
image.addClass('background-img');
// 生成 html 結構
image.wrap(this.wrapper)
.wrap('<div class="crop-work-area"/>')
.wrap('<div class="crop-background"/>');
this.wrapper = $('.image-cropper-wrapper');
$('.crop-work-area', this.wrapper)
.append('<div class="crop-frame"><img class="foreground-img" src="" /></div><div class="drag-containment"/>');
this.wrapper.append(this.zoomWrapper);
$('.image-cropper-wrapper', this.wrapper).disableSelection();
this.reset();
// 拖曳背景圖(同時移動前景圖)
$('.crop-background', this.wrapper).draggable({
containment: $('.drag-containment', this.wrapper),
cursor: 'move',
drag: function(event, ui) {
var self = $(this).data('draggable');
$('.foreground-img', this.wrapper).css({
left: (parseInt(self.position.left) - context.settings.cropFrameRect.left - 1) + 'px',
top: (parseInt(self.position.top) - context.settings.cropFrameRect.top - 1) + 'px'
});
context.settings.left = context.settings.cropFrameRect.left - parseInt($(this).css('left'));
context.settings.top = context.settings.cropFrameRect.top - parseInt($(this).css('top'));
context.fireCallback(context.settings.callbacks.dragging);
}
});
// 拖曳前景圖(同時移動背景)
$('.foreground-img', this.wrapper).draggable({
containment: $('.drag-containment', this.wrapper),
cursor: 'move',
drag: function(event, ui) {
var self = $(this).data('draggable');
$('.crop-background', this.wrapper).css({
left: (parseInt(self.position.left) + context.settings.cropFrameRect.left + 1) + 'px',
top: (parseInt(self.position.top) + context.settings.cropFrameRect.top + 1) + 'px'
});
context.settings.left = context.settings.cropFrameRect.left - parseInt($('.crop-background', this.wrapper).css('left'));
context.settings.top = context.settings.cropFrameRect.top - parseInt($('.crop-background', this.wrapper).css('top'));
context.fireCallback(context.settings.callbacks.dragging);
}
});
// 點擊縮放
$('.zoom-out-button,.zoom-in-button', this.wrapper).click(function() {
var step = $(this).hasClass('zoom-in-button')
? context.settings.zoom.step : -context.settings.zoom.step;
var tempZoomLevel = context.formatNumber(context.settings.zoomLevel + step, 3);
// 超出範圍,或縮放後圖片右下角沒蓋住截取框,則取消縮放
if (context.settings.zoomLevel >= context.settings.zoom.min
&& context.settings.zoomLevel <= context.settings.zoom.max
&& parseInt($('.crop-background', this.wrapper).css('left')) + tempZoomLevel * context.img.width > context.settings.cropFrameRect.left + context.settings.width
&& parseInt($('.crop-background', this.wrapper).css('top')) + tempZoomLevel * context.img.height > context.settings.cropFrameRect.top + context.settings.height
) {
context.settings.zoomLevel = tempZoomLevel;
context.zoom(context.img.width * context.settings.zoomLevel,
context.img.height * context.settings.zoomLevel);
$('.zoom-scroller', this.wrapper)
.css('left', context.settings.zoomLevel * 200 / (context.settings.zoom.max - context.settings.zoom.min) + 'px');
}
context.fireCallback(context.settings.callbacks.zoomed);
});
// 捲動條縮放
var cancelZoomScroll = false;
$('.zoom-scroller', this.wrapper).draggable({
containment: $('.zoom-scrollbar', this.wrapper),
axis: 'x',
drag: function(event, ui) {
var tempZoomLevel = (context.settings.zoom.max - context.settings.zoom.min)
* parseInt($(this).css('left')) / 200;
if (parseInt($('.crop-background', this.wrapper).css('left')) + tempZoomLevel * context.img.width > context.settings.cropFrameRect.left + context.settings.width
&& parseInt($('.crop-background', this.wrapper).css('top')) + tempZoomLevel * context.img.height > context.settings.cropFrameRect.top + context.settings.height
) {
context.settings.zoomLevel = tempZoomLevel;
context.zoom(context.img.width * context.settings.zoomLevel,
context.img.height * context.settings.zoomLevel);
cancelZoomScroll = false;
context.fireCallback(context.settings.callbacks.zoomed);
} else {
cancelZoomScroll = true;
}
},
stop: function(event, ui) {
// 若這次縮放無效,把捲軸歸位
if (cancelZoomScroll) {
$('.zoom-scroller', this.wrapper)
.css('left', context.settings.zoomLevel * 200 / (context.settings.zoom.max - context.settings.zoom.min) + 'px');
}
}
});
},
reset: function() {
this.img = new Image();
this.img.src = this.settings.imagePath;
// 截取框大於工作區時,放大工作區
var tempSize = {
width: Math.max(this.settings.cropWorkAreaSize.width, this.settings.width),
height: Math.max(this.settings.cropWorkAreaSize.height, this.settings.height)
};
// 截取框在工作區中居中
if (this.settings.cropFrameRect.center) {
this.settings.cropFrameRect.left = (tempSize.width - this.settings.width) / 2;
this.settings.cropFrameRect.top = (tempSize.height - this.settings.height) / 2;
}
// 截取框在圖片中居中
if (this.settings.center) {
this.settings.left = (this.img.width * this.settings.zoomLevel - this.settings.width) / 2;
this.settings.top = (this.img.height * this.settings.zoomLevel - this.settings.height) / 2;
}
this.wrapper.width(tempSize.width + 2).height(tempSize.height + 25);
$('.foreground-img,.background-img', this.wrapper).attr('src', this.settings.imagePath);
$('.crop-work-area', this.wrapper).width(tempSize.width).height(tempSize.height);
$('.crop-frame', this.wrapper).css({
left: this.settings.cropFrameRect.left + 'px',
top: this.settings.cropFrameRect.top + 'px',
width: this.settings.width + 'px',
height: this.settings.height + 'px'
});
$('.foreground-img', this.wrapper).css({
left: (-this.settings.cropFrameRect.left - 1) + 'px',
top: (-this.settings.cropFrameRect.top - 1) + 'px'
});
$('.zoom-scroller', this.wrapper)
.css('left', this.settings.zoomLevel * 200 / (this.settings.zoom.max - this.settings.zoom.min) + 'px');
$('.crop-background', this.wrapper).css({
opacity: 0.3,
left: this.settings.cropFrameRect.left - this.settings.left + 'px',
top: this.settings.cropFrameRect.top - this.settings.top + 'px'
});
$('.foreground-img', this.wrapper).css({
left: -this.settings.left + 'px',
top: -this.settings.top + 'px'
});
this.settings.left = this.settings.cropFrameRect.left - parseInt($('.crop-background', this.wrapper).css('left'));
this.settings.top = this.settings.cropFrameRect.top - parseInt($('.crop-background', this.wrapper).css('top'));
this.zoom(this.img.width * this.settings.zoomLevel,
this.img.height * this.settings.zoomLevel);
},
zoom: function(width, height) {
$('.crop-background, .background-img, .foreground-img', this.wrapper)
.width(width).height(height);
// 調整拖曳限制框
$('.drag-containment', this.wrapper).css({
left: this.settings.cropFrameRect.left + this.settings.width - this.settings.zoomLevel * this.img.width + 1 + 'px',
top: this.settings.cropFrameRect.top + this.settings.height - this.settings.zoomLevel * this.img.height + 1 + 'px',
width: 2 * this.settings.zoomLevel * this.img.width - this.settings.width + 'px',
height: 2 * this.settings.zoomLevel * this.img.height - this.settings.height + 'px'
});
},
formatNumber: function(number, bit) {
return Math.round(number * Math.pow(10, bit)) / Math.pow(10, bit);
},
fireCallback: function(fn) {
if ($.isFunction(fn)) { fn.call(this); }
}
};
})(jQuery);
整個外掛用「三層同大小、同步位移」的技巧做出裁切框效果:背景圖(半透明)與前景圖(清晰)疊在一起,中間挖一個 .crop-frame 的視窗,前景圖以負位移對齊,看起來就像框選。拖曳任一張圖時另一張同步移動,並隨時更新 settings.left / settings.top。
縮放時有兩個防呆設計:一是縮放級別不得超出 zoom.min~zoom.max,二是縮放後圖片必須仍能完全覆蓋裁切框,否則不予變更(捲軸會歸位)。這確保送到後端的座標永遠落在原圖範圍內。
p 參數。直接拿使用者傳入的路徑去 MapPath 與 Image.FromFile,等於開了一個任意檔案讀取的入口,建議改成白名單對應。Image.FromFile 會鎖住檔案,同圖連續裁切可能出錯;實務上多改用 Image.FromStream 搭配 FileStream 並妥善關閉。new Image() 可能尚未載入完成就讀取寬高。建議加上 onload 等待,或改用 jQuery 的 .load()。