我想在使用javascript或jQuery在客户端上传到服务器之前剪切和压缩图像。Javascript修剪图像客户端
工作流程:
- 选择图片
- 裁剪图像要具体尺寸
- 压缩农作物
- 上传
有没有人这样做呢?什么插件或我必须做什么?
我看facebook可以在上传前压缩图像并自动调整大小。
我想在使用javascript或jQuery在客户端上传到服务器之前剪切和压缩图像。Javascript修剪图像客户端
工作流程:
有没有人这样做呢?什么插件或我必须做什么?
我看facebook可以在上传前压缩图像并自动调整大小。
EDIT(2014):这个答案现在已经过时了! JavaScript是一种编程语言,它的实现受到了哪些浏览器资源可用的影响,因此受到深度影响 。三个 年前,当这个职位(2011年7月)浏览器没有任何 种可靠的功能,这将允许OP做他所要求的,因此我的答案。
如果您仍然对如何完成这项工作感兴趣,请参考这个问题的许多答案,这些问题在SO上同时出现了 。但请限制自己对此答案作出任何进一步评论 ,因为它显然毫无意义。谢谢。
简单地说,JavaScript并不是要做你所要求的。无论您遇到哪种服务,都可以操纵选定的图像,您可以在您提供任何其他功能之前下注图像,以便将图像完全上传到服务器。
它绝对可以做到。看看这里:http://stackoverflow.com/questions/12728188/cropping-images-in-the-browser-before-the-upload/12730031#12730031 –
这个答案是两年前,当大量的HTML5的东西甚至都不存在,并且正在执行图像处理的所有服务都在服务器端进行。 – brezanac
我编码js超过6年,我不想争论2年前可以做什么或不可以做什么。最重要的是,这个线程仍然是*我们*时代的热门*,它值得更新的答案。 –
您可以使用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);
}
小菜一碟;)
评论评论:感谢您的回答,欢迎来到SO。只是一个提示:回答很好,但更好的解释你的解决方案的每一步。 –
mime在* toDataURL('image/jpg',90)*中需要* jpeg * not * jpg *。谢谢你的伟大答案。 – Kareem
现代浏览器现在可以通过jQuery和HTML5画布支持很多图像处理的。可用于实现这一目标的工具包括:
Resize & Crop for Jquery (ClientSide)
Pixastic Image Processing Library
HTML5 Canvas Image Optimization
我希望证明为寻找类似的解决方案有用...
呃关心评论downvoter? –
我不知道这是否可能。 Facebook可能会拍摄您上传的任何图像,在服务器上重新调整大小,然后保存它们。然后,您会看到图片在页面上重新调整大小。如果你想调整PHP的代码,我已经开发了一些代码。唯一的问题是,我没有不透明度为调整大小的PNG工作。 – James