Javascript裁剪图像客户端

Sha*_*ean 6 javascript jquery image-processing

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

工作流程:

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

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

我看到facebook可以压缩图像并在上传之前自动调整大小.

Adr*_*oni 15

您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)

小菜一碟 ;)

  • 评论评论:感谢您的回答,欢迎来到SO.只是一个提示:回答很好,但更理解你的解决方案的每一步. (3认同)

bre*_*nac 5

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

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

  • 我同意,但是让自己处于这种情况:你是这个网站的新手,你想要OP在这个问题上想要的东西......**正确**和**接受的答案是:"不!它无法完成!" 当问到这个问题时,我不是说**这是可能的**,但**现在是**,答案应该更新.想象一下,在大多数主题上,网络(也是如此)充满了过时和错误的资源......这将是一个多么酷的世界? (3认同)
  • 这个答案是在两年前做出的,当时很多HTML5的东西都不存在,并且每个服务器都在执行图像处理的情况下在服务器端执行. (2认同)
  • @ gion_13,但你所指的答案和那里发生的过程纯粹是浏览器的作用,而且正如holodoc所说,JS仍然无法实现.这可以在浏览器的帮助下完成 (2认同)