Sha*_*ean 6 javascript jquery image-processing
我想在上传到服务器之前使用javascript或jQuery在客户端裁剪和压缩图像.
工作流程:
有没有人这样做过?什么插件或我该怎么办?
我看到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)
小菜一碟 ;)
编辑(2014):这个答案现在已经过时了!JavaScript是一种编程语言,其实现深受可供浏览器资源使用的影响.三年前,当这篇文章发表时(2011年7月),浏览器没有任何可靠的功能,这将允许OP做他所要求的,因此我的回答.
如果你现在仍然对如何做到这一点感兴趣,请参考这个问题的许多答案,这些答案在SO同时出现.但是请不要对这个答案做出任何进一步的评论,因为它显然毫无意义.谢谢.
简单地说,JavaScript并不意味着要做你想要的.无论您遇到哪种服务都可以操作选定的图像,您可以在提供任何其他功能之前将图像完全上传到服务器.