/**
* 图片压缩上传
* @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压缩的方法的更多相关文章

  1. springMVC两种方式实现多文件上传及效率比较

    springMVC实现 多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传.这两种方式对于实 现多文件上传效率上却有着很大的 ...

  2. 动态input file多文件上传到后台没反应的解决方法!!!

    其实我也不太清除具体是什么原因,但是后面就可以了!!! 我用的是springMVC 自带的文件上传 1.首先肯定是要有springMVC上传文件的相关配置! 2.前端 这是动态input file上传 ...

  3. win服务器 文件上传下载出现“未指定的错误” 解决方法汇总

    环境 WIN平台IIS服务器   经常出现于ASPX页面 汇总 1.权限问题 出现场景 : 基于ACCESS数据库   原因解析 : 1.首先需要排除自身问题,例如建表使用关键字,格式错误,插入数据与 ...

  4. 体验三大JavaScript文件上传库(Uppy.js/Filepond/Dropzone)

    最近发现了一个高颜值的前端上传组件Uppy.js,立即上手体验了一波,感觉还不错.然后又看到同类型的Filepond以及Dropzone.js,对比体验了一下,感觉都很优秀,但是在体验过程中,都遇到了 ...

  5. Asp.Net 无刷新文件上传并显示进度条的实现方法及思路

    相信通过Asp.Net的服务器控件上传文件在简单不过了,通过AjaxToolkit控件实现上传进度也不是什么难事,为什么还要自己辛辛苦苦来 实现呢?我并不否认”拿来主义“,只是我个人更喜欢凡是求个所以 ...

  6. 头像文件上传 方法一:from表单 方法二:ajax

    方法一:from表单 html 设置form表单,内包含头像预览div,内包含上传文件input 设置iframe用来调用函数传参路径 <!--表单提交成功后不跳转处理页面,而是将处理数据返回给 ...

  7. JQuery文件上传插件JQuery.upload.js的用法简介

    JQuery文件上传插件,这个插件很小,用法很简单,效果却很棒.注意:JQuery版本要求1.8及以上,大家执行如果没效果,则检查JQuery版本,如果是1.8及以上,则该插件源码中的.size()需 ...

  8. 文件上传时jquery.form.js中提示form.submit SCRIPT5: 拒绝访问

    利用其它控件触发file的click事件来选择文件后,使用jquery.form.js中的submit方法提交时IE报错:form.submit SCRIPT5: 拒绝访问,其它浏览器正常, < ...

  9. dos编辑文件上传到unix系统多余^M删除方法

    linux上的文件sz到window编辑后多出^M, 方法一: 1.grep -anR '^M' filename |wc -l2.crontab -e 或vim filename3.:set ff  ...

随机推荐

  1. 基于unity3d的RRT算法路径规划

  2. iOS Simulator hang up ( Xcode4.6.3)

    最近遇见个Xcode的bug,搞的十分郁闷. 具体现象是:程序前段时间都是好好的,可以运行,第二天开机,调试就无法进入模拟器.就连main()函数都进不了.模拟器完全挂起了.具体说来就是代码一句都没改 ...

  3. SDUT 3361 数据结构实验之图论四:迷宫探索

    数据结构实验之图论四:迷宫探索 Time Limit: 1000MS Memory Limit: 65536KB Submit Statistic Problem Description 有一个地下迷 ...

  4. 《Maven实战》笔记-5-pom聚合和继承

    一.聚合 假设有两个模块:account-email和account-persist: 能够使用一条命令就能构建上述两个模块,需要创建一个额外的模块:account-aggregator: 通过acc ...

  5. [译]Javascript中的函数

    本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...

  6. 用Pdg2.DLL解码PDG的境界

    作者:马健邮箱:stronghorse_mj@hotmail.com发布:2008.08.03 一.入门级原理:按照<用BCB实现超星格式转换为BMP格式>中说的方法调用Pdg2.DLL接 ...

  7. FPM工具 实战定制nginx包

    FPM主要特点: 把一种包打包成另一种包的格式 支持的源类型包 DIR 将目录打包成所需要的类型,可以用于源码编译的安装包. RPM    对rpm进行转换 gem    对rubygem包进行转换. ...

  8. Installing the .NET Framework 3.5 on Windows 8, Windows 8.1 and Windows 10

    Installing the .NET Framework 3.5 on Windows 8, Windows 8.1 and Windows 10 .NET Framework (current v ...

  9. 【机器学习】李宏毅机器学习-Keras-Demo-神经网络手写数字识别与调参

    参考: 原视频:李宏毅机器学习-Keras-Demo 调参博文1:深度学习入门实践_十行搭建手写数字识别神经网络 调参博文2:手写数字识别---demo(有小错误) 代码链接: 编程环境: 操作系统: ...

  10. django 基础框架学习 (一)

    Django-01 Web框架 1.Web应⽤程序处理流程  : 2.Web框架的意义            1.⽤于搭建Web应⽤程序            2.免去不同Web应⽤相同代码部分的重复 ...