通过 Javascript 调整图像大小 [英] Image resize by Javascript

查看:33
本文介绍了通过 Javascript 调整图像大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行网络应用程序.它使用ajax上传.问题是最近用户上传了太大的图像.所以它需要更多的时间.用户对此抱怨不已.所以我在想的是,如果我以某种方式通过 js 裁剪和调整图像大小,然后通过 ajax 上传将其发送到服务器,那么时间将减少".那么有没有办法做到这一点?有什么想法吗?

I've web app running. And it uses ajax upload. The issue is recently users are uploading too big images. So it's taking a bit more time. Users are complaining about that. So what I was thinking is this, 'If I somehow crop and resize the image via js and then send it to the server via ajax upload then the time will be reduced'. So is there any way to do that? Any idea for it?

推荐答案

一个解决方案是使用像 FileReader 和 Canvas 这样的现代方式(但这仅适用于最新的现代浏览器).

A solution is to use modern ways like FileReader and Canvas (But this works only on the latest modern browsers).

http://caniuse.com/filereader

http://caniuse.com/canvas

在这个例子中,我展示了如何让客户端在上传之前通过设置最大宽度来调整图像大小 &高度保持纵横比.

In this example i show how to let the client resize an image before uploading by setting a max width & height mantaining aspect ratio.

在这个例子中最大宽度高度 = 64;你的最终图像是 c.toDataURL();

In this example max widthHeight = 64; your final image is 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>

在代码的画布部分还可以添加裁剪功能.

In the canvas part of the code you can also add a cropping function.

按照评论中的要求进行编辑

c.toDataURL();

是图像 base64_string,您可以将其存储在隐藏输入中,附加到 new FormData() 或任何您想要的位置.

is the image base64_string you can store it in a hidden input,append to a new FormData() or wherever you want.

在服务器上

$data=explode(',',$base64_string);
$image=base64_decode($data[1]);

写入文件

$f=fopen($fileName,"wb");
fwrite($f,$image); 
fclose($f);

$gd=imagecreatefromstring($image);

您还可以将整个 base64 图像字符串存储在数据库中并始终使用它.

you can also store the whole base64 image string in the database and always use that.

这篇关于通过 Javascript 调整图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆