您依靠裁剪工具为用户提供界面。问题是返回的图像大小适合界面而不是原始图像。而不是我筛选各种 API 来查看它们是否提供了某种控制这种行为的方法(我假设至少其中一些会),因为这是一个如此简单的过程,我将展示如何手动裁剪图像。
以 JCrop 为例
jcrop为cropstart、cropmove、cropend提供了各种事件……你可以添加一个监听器来监听这些事件,并保留一份当前裁剪界面状态的副本
var currentCrop;
jQuery('#target').on('cropstart cropmove cropend',function(e,s,crop){
currentCrop = crop;
}
我不知道你在哪里设置了界面大小,我假设事件返回界面比例的裁剪细节
var interfaceSize = { //you will have to work this out
w : ?,
h : ?.
}
你的原图
var myImage = new Image(); // Assume you know how to load
因此,当单击裁剪按钮时,您可以通过将裁剪细节缩放回原始图像大小来创建新图像,以裁剪大小创建画布,绘制图像以正确定位裁剪区域并返回画布原样或作为新图像。
// image = image to crop
// crop = the current cropping region
// interfaceSize = the size of the full image in the interface
// returns a new cropped image at full res
function myCrop(image,crop,interfaceSize){
var scaleX = image.width / interfaceSize.w; // get x scale
var scaleY = image.height / interfaceSize.h; // get y scale
// get full res crop region. rounding to pixels
var x = Math.round(crop.x * scaleX);
var y = Math.round(crop.y * scaleY);
var w = Math.round(crop.w * scaleX);
var h = Math.round(crop.h * scaleY);
// Assume crop will never pad
// create an drawable image
var croppedImage = document.createElement("canvas");
croppedImage.width = w;
croppedImage.height = h;
var ctx = croppedImage.getContext("2d");
// draw the image offset so the it is correctly cropped
ctx.drawImage(image,-x,-y);
return croppedImage
}
然后你只需要在点击裁剪按钮时调用这个函数
var croppedImage;
myButtonElement.onclick = function(){
if(currentCrop !== undefined){ // ensure that there is a selected crop
croppedImage = myCrop(myImage,currentCrop,interfaceSize);
}
}
您可以将图片转换为dataURL以供下载,并通过
imageData = croppedImage.toDataURL(mimeType,quality) // quality is optional and only for "image/jpeg" images