Javascript裁剪图像客户端

我想在上传到服务器之前使用javascript或jQuery在客户端裁剪和压缩图像。

工作流程:

  1. 选择图像
  2. 将图像裁剪为特定尺寸
  3. 压缩作物
  4. 上传

有没有人这样做过? 什么插件或我该怎么办?

我看到facebook可以压缩图像并在上传前自动resize。

编辑(2014):这个答案现在已经过时了! JavaScript是一种编程语言,其实现深受可用于哪些浏览器资源的影响。 三年前,当这篇文章发表时(2011年7月),浏览器没有任何可靠的function,这将允许OP做他所要求的,因此我的答案。
如果你现在仍然对如何做到这一点感兴趣,请参考这个问题的许多答案,这些答案在SO同时出现。 但是请不要对这个答案做出任何进一步的评论,因为它显然毫无意义。 谢谢。

简单地说,JavaScript并不意味着要做你想要的。 无论您遇到哪种服务都可以操作选定的图像,您可以在提供任何其他function之前将图像完全上传到服务器。

您可以使用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); } 

小菜一碟 ;)

现代浏览器现在通过jquery和html5 canvas支持大量图像处理。 可用于实现此目的的工具包括:

为Jqueryresize和裁剪(ClientSide)

像素图像处理库

HTML5canvas图像优化

我希望这对于寻找类似解决方案的人来说非常有用……