2009-06-07 149 views
51

我需要提供一种方法让用户以jpeg格式将照片上传到他们的网站。不过,这些照片在原始尺寸上非常大,我想在上传前调整大小选项,让用户非常轻松。看起来我唯一的选择是客户端应用程序,它在通过Web服务上传照片之前调整照片大小,或者调整图像大小的上载操作的客户端JavaScript钩子。第二个选项非常具有临时性,因为我没有JavaScript图像调整大小库,并且很难让JavaScript运行我当前的大小调整工具ImageMagick。上传前调整图片的大小

我敢肯定,这不是一个不常见的情况,一些建议或指向这样做的网站将不胜感激。

回答

7

您有几种选择:

  1. 的Java
  2. 的ActiveX(仅适用于Windows)
  3. Silverlight
  4. Flash
  5. Flex
  6. Google Gears(最新的版本是能够调整的并从桌面上拖放)

我已经做了大量的研究寻找类似的解决方案,你所描述的,并有很多的解决方案,在质量和灵活性有很大的不同。

我的建议是找到一个解决方案,它将完成您需要的80%,并根据您的需求进行定制。

+2

谷歌齿轮得到删除? – 2012-06-06 14:26:45

+2

是的,我的谷歌齿轮建议是在删除之前做的(注意我的答案的日期)。 – digitalsanctum 2012-06-06 17:40:43

1

不幸的是,您将无法使用Javascript调整图像大小。在Silverlight 2 tho中是可能的。

如果你想购买已经完成的东西:Aurigma Image Uploader是相当令人印象深刻的 - ActiveX和Java版本$ USD250。网站上有一些演示,我很确定Facebook使用相同的控制。

2

jao和russau说的是真的。原因是由于安全原因,JavaScript无法访问本地文件系统。如果JavaScript能够“看到”你的图像文件,它可以看到任何文件,这是危险的。

您需要一个应用程序级控件才能做到这一点,这意味着Flash,Java或Active-X。

61

2011年,我们可以通过File API和canvas来了解它。 这只适用于firefox和chrome。 以下是一个示例:

var file = YOUR_FILE, 
    fileType = file.type, 
    reader = new FileReader(); 

reader.onloadend = function() { 
    var image = new Image(); 
     image.src = reader.result; 

    image.onload = function() { 
    var maxWidth = 960, 
     maxHeight = 960, 
     imageWidth = image.width, 
     imageHeight = image.height; 

    if (imageWidth > imageHeight) { 
     if (imageWidth > maxWidth) { 
     imageHeight *= maxWidth/imageWidth; 
     imageWidth = maxWidth; 
     } 
    } 
    else { 
     if (imageHeight > maxHeight) { 
     imageWidth *= maxHeight/imageHeight; 
     imageHeight = maxHeight; 
     } 
    } 

    var canvas = document.createElement('canvas'); 
    canvas.width = imageWidth; 
    canvas.height = imageHeight; 

    var ctx = canvas.getContext("2d"); 
    ctx.drawImage(this, 0, 0, imageWidth, imageHeight); 

    // The resized file ready for upload 
    var finalFile = canvas.toDataURL(fileType); 
    } 
} 

reader.readAsDataURL(file); 
0

纯JavaScript解决方案。我的代码通过双线性插值调整JPEG大小,并且不会丢失exif。

https://github.com/hMatoba/JavaScript-MinifyJpegAsync

function post(data) { 
    var req = new XMLHttpRequest(); 
    req.open("POST", "/jpeg", false); 
    req.setRequestHeader('Content-Type', 'image/jpeg'); 
    req.send(data.buffer); 
} 

function handleFileSelect(evt) { 
    var files = evt.target.files; 

    for (var i = 0, f; f = files[i]; i++){ 
     var reader = new FileReader(); 
     reader.onloadend = function(e){ 
      MinifyJpegAsync.minify(e.target.result, 1280, post); 
     }; 
     reader.readAsDataURL(f); 
    } 
} 

document.getElementById('files').addEventListener('change', handleFileSelect, false);