几种经过整理的文件上传压缩和前台js压缩的方法
/**
* 图片压缩上传
* @param $im,图片资源
* @param int $maxwidth,最大宽度,超过这个宽度则进行压缩
* @param int $maxheight,最大高度,超过这个高度则进行压缩
* @param $name,图片名,完整的路径加名称
* @param $filetype,图片类型
* @return bool
*/
function thumbImage($im,$name,$filetype,$maxwidth=800,$maxheight=920)
{
switch ($filetype) {
case 'image/jpg':
case 'image/jpeg':
$im = imagecreatefromjpeg($im); //PHP图片处理系统函数
break;
case 'image/gif':
$im = imagecreatefromgif($im);
break;
case 'image/png':
$im = imagecreatefrompng($im);
break;
case 'image/wbmp':
$im = imagecreatefromwbmp($im);
break;
} $resizewidth_tag = $resizeheight_tag = false;
$pic_width = imagesx($im);
$pic_height = imagesy($im); if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
{
$resizewidth_tag = $resizeheight_tag = false; if($maxwidth && $pic_width>$maxwidth)
{
$widthratio = $maxwidth / $pic_width;
$resizewidth_tag = true;
} if($maxheight && $pic_height>$maxheight)
{
$heightratio = $maxheight / $pic_height;
$resizeheight_tag = true;
} if($resizewidth_tag && $resizeheight_tag)
{
if($widthratio < $heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
} if($resizewidth_tag && !$resizeheight_tag)
$ratio = $widthratio; if($resizeheight_tag && !$resizewidth_tag)
$ratio = $heightratio; $newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio; if(function_exists("imagecopyresampled"))
{
$newim = imagecreatetruecolor($newwidth,$newheight);//PHP图片处理系统函数
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP图片处理系统函数
}
else
{
$newim = imagecreate($newwidth,$newheight);
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
} switch ($filetype) {
case 'image/jpg' :
case 'image/jpeg' :
$result = imagejpeg($newim,$name);
break;
case 'image/gif' :
$result = imagegif($newim,$name);
break;
case 'image/png' :
$result = imagepng($newim,$name);
break;
case 'image/wbmp' :
$result = imagewbmp($newim,$name);
break;
}
imagedestroy($newim);
}
else
{
switch ($filetype) {
case 'image/jpg' :
case 'image/jpeg' :
$result = imagejpeg($im,$name);
break;
case 'image/gif' :
$result = imagegif($im,$name);
break;
case 'image/png' :
$result = imagepng($im,$name);
break;
case 'image/wbmp' :
$result = imagewbmp($im,$name);
break;
}
}
return $result;
} /**
* 图片不改变长宽吗,压缩清晰度
* @param $img,'http://www.phpernote.com/images/logo.png' 或者 public/timg.jpg
* @param $path, public/frontend/xxx.jpg 保存新图片的地址
*/
function dirthumbImage($img,$filename,$quality=20){
$imgInfo = pathinfo($img);
$filetype = $imgInfo['extension'];
switch ($filetype) {
case 'gif':
$image = imagecreatefromgif($img);
header("Content-type:image/gif");
break;
case 'png':
$image = imagecreatefrompng($img);
header("Content-type:image/png");
break;
case 'wbmp':
$image = imagecreatefromwbmp($img);
header("Content-type:image/wbmp");
break;
default:
$image=imagecreatefromjpeg($img); //PHP图片处理系统函数 jpg、jpeg
header("Content-type:image/jpeg");
} if(empty($filename)) $filename=$img;//如果储存文件为空,那么替换原来的文件
imagejpeg($image,$filename,$quality); //注意后面那个数字0,这里即压缩等级,参数范围:0-9*/
imagedestroy($image);
} /**
* 将base64编码转换为图片保存至指定位置
* @param $dir,保存的路径public/frontend/uplode/user
* @param $filename,图片的名称
* @param $base64,图片base64编码
* @param $typeList,允许的图片类型 'jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG','gif','GIF'
* @return array
*/
function saveBase64($dir,$filename,$base64,$typeList){
header('Content-type:text/html;charset=utf-8');
preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result);
$type = $result[2]; //获取图片的类型jpg png等
if(empty($typeList)) $typeList = [ 'jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG','gif','GIF'];//文件允许的类型
if(!in_array($type,$typeList)){
return array('error'=>2,'msg'=>'图片格式错误');
}
$name =$filename.'.'.$type; //图片重命名
$savepath = $dir.'/'.$name; //图片保存目录
if(file_put_contents($savepath, base64_decode(str_replace($result[1], '', $base64)))) { //对图片进行解析并保存
return array('error'=>0,'msg'=>'保存成功','file_path'=>$savepath);
}else{
return array('error'=>1,'msg'=>'保存失败');
}
} function imgToBase64($img_file) { $img_base64 = '';
if (file_exists($img_file)) {
$app_img_file = $img_file; // 图片路径
$img_info = getimagesize($app_img_file); // 取得图片的大小,类型等 //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
$fp = fopen($app_img_file, "r"); // 图片是否可读权限 if ($fp) {
$filesize = filesize($app_img_file);
$content = fread($fp, $filesize);
$file_content = chunk_split(base64_encode($content)); // base64编码
switch ($img_info[2]) { //判读图片类型
case 1: $img_type = "gif";
break;
case 2: $img_type = "jpg";
break;
case 3: $img_type = "png";
break;
} $img_base64 = $file_content;//合成图片的base64编码 }
fclose($fp);
} return $img_base64; //返回图片的base64
}
/**
* 获取图片的Base64编码(不支持url)
* @param $img_file 传入本地图片地址
* @return string
*/
function imgToBase64($img_file) { $img_base64 = '';
if (file_exists($img_file)) {
$app_img_file = $img_file; // 图片路径
$img_info = getimagesize($app_img_file); // 取得图片的大小,类型等 //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
$fp = fopen($app_img_file, "r"); // 图片是否可读权限 if ($fp) {
$filesize = filesize($app_img_file);
$content = fread($fp, $filesize);
$file_content = chunk_split(base64_encode($content)); // base64编码
switch ($img_info[2]) { //判读图片类型
case 1: $img_type = "gif";
break;
case 2: $img_type = "jpg";
break;
case 3: $img_type = "png";
break;
} $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码 }
fclose($fp);
} return $img_base64; //返回图片的base64
}
JS前台压缩
//图片上传
function b(obj,id) {
var r= new FileReader();
f=document.getElementById(id).files[0];
if(f==undefined){return false;}
r.readAsDataURL(f);
r.onload=function (e) {
//图片压缩
// 调用函数处理图片
dealImage(this.result, {
// 注意:在pc端可以用绝对路径或相对路径,移动端最好用绝对路径(因为用take photo后的图片路径,我没有试成功(如果有人试成功了可以分享一下经验))
width : 800
}, function(base){
//直接将获取到的base64的字符串,放到一个image标签中就可看到测试后的压缩之后的样式图了
console.log("压缩后:" + base.length / 1024 + " " + base); }); };
} /**
* 图片压缩,默认同比例压缩
* @param {Object} path
* pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
* @param {Object} obj
* obj 对象 有 width, height, quality(0-1)
* @param {Object} callback
* 回调函数有一个参数,base64的字符串数据
*/
function dealImage(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.9; // 默认图片质量为0.5
//生成canvas
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
// 创建属性节点
var anw = document.createAttribute("width");
anw.nodeValue = w;
var anh = document.createAttribute("height");
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL('image/jpeg', quality );
// 回调函数返回base64的值
callback(base64);
}
}
几种经过整理的文件上传压缩和前台js压缩的方法的更多相关文章
- springMVC两种方式实现多文件上传及效率比较
springMVC实现 多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传.这两种方式对于实 现多文件上传效率上却有着很大的 ...
- 动态input file多文件上传到后台没反应的解决方法!!!
其实我也不太清除具体是什么原因,但是后面就可以了!!! 我用的是springMVC 自带的文件上传 1.首先肯定是要有springMVC上传文件的相关配置! 2.前端 这是动态input file上传 ...
- win服务器 文件上传下载出现“未指定的错误” 解决方法汇总
环境 WIN平台IIS服务器 经常出现于ASPX页面 汇总 1.权限问题 出现场景 : 基于ACCESS数据库 原因解析 : 1.首先需要排除自身问题,例如建表使用关键字,格式错误,插入数据与 ...
- 体验三大JavaScript文件上传库(Uppy.js/Filepond/Dropzone)
最近发现了一个高颜值的前端上传组件Uppy.js,立即上手体验了一波,感觉还不错.然后又看到同类型的Filepond以及Dropzone.js,对比体验了一下,感觉都很优秀,但是在体验过程中,都遇到了 ...
- Asp.Net 无刷新文件上传并显示进度条的实现方法及思路
相信通过Asp.Net的服务器控件上传文件在简单不过了,通过AjaxToolkit控件实现上传进度也不是什么难事,为什么还要自己辛辛苦苦来 实现呢?我并不否认”拿来主义“,只是我个人更喜欢凡是求个所以 ...
- 头像文件上传 方法一:from表单 方法二:ajax
方法一:from表单 html 设置form表单,内包含头像预览div,内包含上传文件input 设置iframe用来调用函数传参路径 <!--表单提交成功后不跳转处理页面,而是将处理数据返回给 ...
- JQuery文件上传插件JQuery.upload.js的用法简介
JQuery文件上传插件,这个插件很小,用法很简单,效果却很棒.注意:JQuery版本要求1.8及以上,大家执行如果没效果,则检查JQuery版本,如果是1.8及以上,则该插件源码中的.size()需 ...
- 文件上传时jquery.form.js中提示form.submit SCRIPT5: 拒绝访问
利用其它控件触发file的click事件来选择文件后,使用jquery.form.js中的submit方法提交时IE报错:form.submit SCRIPT5: 拒绝访问,其它浏览器正常, < ...
- dos编辑文件上传到unix系统多余^M删除方法
linux上的文件sz到window编辑后多出^M, 方法一: 1.grep -anR '^M' filename |wc -l2.crontab -e 或vim filename3.:set ff ...
随机推荐
- p4322 [JSOI2016]最佳团体
传送门 分析 我们不难发现这是一棵树 于是01分数规划然后树上dp即可 代码 #include<iostream> #include<cstdio> #include<c ...
- cakephp目录结构
- Entity Framework Tutorial Basics(6):Model Browser
Model Browser: We have created our first Entity Data Model for School database in the previous secti ...
- SDUT 2142 数据结构实验之图论二:基于邻接表的广度优先搜索遍历
数据结构实验之图论二:基于邻接表的广度优先搜索遍历 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic Problem Descript ...
- 第二周个人作业:WordCount
github地址 https://github.com/lzwk/WordCount PSP表格 PSP2.1 PSP阶段 预估耗时(分钟) 实际耗时(分钟) Planning 计划 20 40 · ...
- 记一次OOM问题排查过程
上周运维反馈线上程序出现了OOM,程序日志中的输出为 Exception in thread "http-nio-8080-exec-1027" java.lang.OutOfMe ...
- Redhat 6 git服务器配置 (git-daemon)
git-daemon是按照git的自己的git协议进行访问git服务 1.git-daemon软件安装 软件仓库见 redhat 6 git 服务器 配置 (http) 2.配置git dae ...
- CentOS6.5上Zabbix3.0的RPM安装【三】-安装并添加Agent
七.Download and install Zabbix Agent Zabbix Agent is required to install on all remote systems needs ...
- mac的idea不能编辑问题
在安装的时候,因为在选择插件的时候,把IDEAVim这个玩意儿选上了.所以,编辑模式就跟命令行里面的Vim一样.输入时,需要先输入i, 进入insert模式下,然后才可以编辑.彻底解决办法就是进入Pr ...
- vtk-py求3d模型表面积
模型格式:.obj 环境:python3.6+vtk7.1 vtk版: import vtk filename = "XXXX.obj" reader = vtk.vtkOBJRe ...