通过Javascript调整图像大小

Image resize by Javascript

本文关键字:图像 调整 Javascript 通过      更新时间:2023-09-26

我已经运行了web应用程序。它使用ajax上传。问题是最近用户上传的图片太大。所以这需要更多的时间。用户对此颇有怨言。所以我想的是,"如果我通过js裁剪并调整图像大小,然后通过ajax上传将其发送到服务器,那么时间就会减少"。那么有什么办法可以做到这一点吗?有什么想法吗?

解决方案是使用现代方式,如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>

在代码的画布部分,您还可以添加一个裁剪函数。


根据评论中的要求进行编辑

c.toDataURL();

是基于图像的64_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图像字符串存储在数据库中,并始终使用它。