一种解决方案是使用 FileReader 和 Canvas 等现代方式(但这仅适用于最新的现代浏览器)。
http://caniuse.com/filereader
http://caniuse.com/canvas
在这个例子中,我展示了如何让客户端在上传之前通过设置最大宽度和高度来调整图像大小,以维持纵横比。
在此示例中,最大宽度高度 = 64;
你的最终图像是 c.toDataURL();
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script>
var h=function(e){
var fr=new FileReader();
fr.onload=function(e){
var img=new Image();
img.onload=function(){
var MAXWidthHeight=64;
var r=MAXWidthHeight/Math.max(this.width,this.height),
w=Math.round(this.width*r),
h=Math.round(this.height*r),
c=document.createElement("canvas");
c.width=w;c.height=h;
c.getContext("2d").drawImage(this,0,0,w,h);
this.src=c.toDataURL();
document.body.appendChild(this);
}
img.src=e.target.result;
}
fr.readAsDataURL(e.target.files[0]);
}
window.onload=function(){
document.getElementById('f').addEventListener('change',h,false);
}
</script>
</head>
<body>
<input type="file" id="f">
</body>
</html>
在代码的画布部分还可以添加裁剪功能。
按照 cmets 中的要求进行编辑
c.toDataURL();
是图像 base64_string,您可以将其存储在隐藏输入中,附加到 new FormData() 或您想要的任何位置。
在服务器上
$data=explode(',',$base64_string);
$image=base64_decode($data[1]);
写入文件
$f=fopen($fileName,"wb");
fwrite($f,$image);
fclose($f);
或
$gd=imagecreatefromstring($image);
您还可以将整个 base64 图像字符串存储在数据库中并始终使用它。