2011-07-27 40 views
5

我想在使用javascript或jQuery在客戶端上傳到服務器之前剪切和壓縮圖像。Javascript修剪圖像客戶端

工作流程:

  1. 選擇圖片
  2. 裁剪圖像要具體尺寸
  3. 壓縮農作物
  4. 上傳

有沒有人這樣做呢?什麼插件或我必須做什麼?

我看facebook可以在上傳前壓縮圖像並自動調整大小。

+0

我不知道這是否可能。 Facebook可能會拍攝您上傳的任何圖像,在服務器上重新調整大小,然後保存它們。然後,您會看到圖片在頁面上重新調整大小。如果你想調整PHP的代碼,我已經開發了一些代碼。唯一的問題是,我沒有不透明度爲調整大小的PNG工作。 – James

+1

? – spacevillain

回答

6

EDIT(2014):這個答案現在已經過時了! JavaScript是一種編程語言,它的實現受到了哪些瀏覽器資源可用的影響,因此受到深度影響 。三個 年前,當這個職位(2011年7月)瀏覽器沒有任何 種可靠的功能,這將允許OP做他所要求的,因此我的答案。
如果您仍然對如何完成這項工作感興趣,請參考這個問題的許多答案,這些問題在SO上同時出現了 。但請限制自己對此答案作出任何進一步評論 ,因爲它顯然毫無意義。謝謝。

簡單地說,JavaScript並不是要做你所要求的。無論您遇到哪種服務,都可以操縱選定的圖像,您可以在您提供任何其他功能之前下注圖像,以便將圖像完全上傳到服務器。

+0

它絕對可以做到。看看這裏:http://stackoverflow.com/questions/12728188/cropping-images-in-the-browser-before-the-upload/12730031#12730031 –

+2

這個答案是兩年前,當大量的HTML5的東西甚至都不存在,並且正在執行圖像處理的所有服務都在服務器端進行。 – brezanac

+0

我編碼js超過6年,我不想爭論2年前可以做什麼或不可以做什麼。最重要的是,這個線程仍然是*我們*時代的熱門*,它值得更新的答案。 –

11

您可以使用Base64做到這一點,看的網站我的工作:http://www.wordirish.com 所有圖像都在使用HTML5或客戶端操作適用於舊瀏覽器的閃光燈。

你只需要做到這一點:

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); 
} 

小菜一碟;)

+3

評論評論:感謝您的回答,歡迎來到SO。只是一個提示:回答很好,但更好的解釋你的解決方案的每一步。 –

+0

mime在* toDataURL('image/jpg',90)*中需要* jpeg * not * jpg *。謝謝你的偉大答案。 – Kareem