我想使用javascript或jQuery在客户端裁剪和压缩图像,然后再上传到服务器。
工作流程:
1. 选择图像 2. 裁剪图像到特定的尺寸 3. 压缩裁剪后的图像 4. 上传
有人做过这个吗?需要使用哪个插件或者我该怎么做?
我看到Facebook可以在上传之前自动压缩和调整图像大小。
工作流程:
1. 选择图像 2. 裁剪图像到特定的尺寸 3. 压缩裁剪后的图像 4. 上传
有人做过这个吗?需要使用哪个插件或者我该怎么做?
我看到Facebook可以在上传之前自动压缩和调整图像大小。
您可以使用base64完成此操作,可以参考我正在使用的网站:http://www.wordirish.com。所有图像都使用HTML5在客户端进行处理,对于旧浏览器则使用flash。
您只需要这样做:
function thisFunctionShoulBeCallByTheFileuploaderButton(e){
e.preventDefault && e.preventDefault();
var image, canvas, i;
var images = 'files' in e.target ? e.target.files : 'dataTransfer' in e ? e.dataTransfer.files : [];
if(images && images.length) {
for(i in images) {
if(typeof images[i] != 'object') continue;
image = new Image();
image.src = createObjectURL(images[i]);
image.onload = function(e){
var mybase64resized = resizeCrop( e.target, 200, 150 ).toDataURL('image/jpg', 90);
alert(mybase64resized);
}
}
}
}
function resizeCrop( src, width, height ){
var crop = width == 0 || height == 0;
// not resize
if(src.width <= width && height == 0) {
width = src.width;
height = src.height;
}
// resize
if( src.width > width && height == 0){
height = src.height * (width / src.width);
}
// check scale
var xscale = width / src.width;
var yscale = height / src.height;
var scale = crop ? Math.min(xscale, yscale) : Math.max(xscale, yscale);
// create empty canvas
var canvas = document.createElement("canvas");
canvas.width = width ? width : Math.round(src.width * scale);
canvas.height = height ? height : Math.round(src.height * scale);
canvas.getContext("2d").scale(scale,scale);
// crop it top center
canvas.getContext("2d").drawImage(src, ((src.width * scale) - canvas.width) * -.5 , ((src.height * scale) - canvas.height) * -.5 );
return canvas;
}
function createObjectURL(i){
var URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
return URL.createObjectURL(i);
}
易如反掌 ;)
编辑(2014):此答案已过时!JavaScript是一种编程语言,其实现深受浏览器资源的影响。三年前,当这篇文章发布时(2011年7月),浏览器没有任何可靠的功能可以让OP做他所要求的事情,因此我的回答。
如果您仍然对如何完成此操作感兴趣,请查阅在SO上同时出现的许多问题的答案。但请自制不要对此答案发表任何进一步的评论,因为这显然是无意义的。谢谢。
简单地说,JavaScript并不适合您所要求的操作。无论您遇到哪个服务都提供了操作选定图像的能力,您可以打赌在提供任何其他功能之前,该图像已完全上传到服务器。
我希望这对于寻找类似解决方案的任何人都有用...