php 实现图片上传并压缩功能
前段时间由于项目需要,要实现图片上传并且压缩生成缩略图的功能。
接口代码如下:
$allowext = array ( 'png', 'jpg', 'jpeg', 'gif','mp4','doc');
$fileElement = 'file';
$filepath_rel = 'userfiles/upload/chatfile/'.date("Ymd")."/"; // 相对路径
//这里的$FILE_PATH 是网站的根目录
$filepath_abs = $FILE_PATH . $filepath_rel; // 绝对路径
if(!file_exists($filepath_abs))
{
mkdir($filepath_abs,0777,true); }
$fup = new FileUpload ( '100M', $allowext );$r = $fup->upload ( $fileElement, $filepath_abs, '', true );$name_abs = $filepath_abs . $r;$name_rel = $filepath_rel . $r;//图片等比例压缩$pic = $fup->getThumb($FILE_PATH,$name_rel,300,300); //upload 方法实现图片上传
//参数$elename : file域的名称。<input type='file' name='elename'/>
//$newname --上传以后的名字;可以为空。
//$savepath --文件保存路径,一定要以 “/” 结尾。
//$auto_rename 是否自动重命名
//如果$newname 为空 且 auto_rename 为false ,将保留原来的文件名字
function upload($elename, $savepath, $newname = '', $auto_rename = false){
if(empty($_FILES[$elename])) throw new Exception('没有上传文件或文件大小超过系统限制', 981);
$f_name = basename($_FILES[$elename]["name"]); //被上传文件的名称
$f_type = $_FILES[$elename]["type"]; //被上传文件的类型
$f_size = $_FILES[$elename]["size"]; //被上传文件的大小,以字节计
$f_tmpname = $_FILES[$elename]["tmp_name"]; //存储在服务器的文件的临时副本的名称
$f_error = $_FILES[$elename]["error"]; //由文件上传导致的错误代码
//是否发生错误
if($f_error) $this->uploadFileError($f_error);
//文件后缀
$f_ext = $this->getFileExt($f_name);
//检查上传类型
//--是否在禁止列表
$forbidext = $this->forbidext;
if(in_array($f_ext, $forbidext)) {
throw new Exception('文件类型禁止上传', 901);
}
//--是否在允许列表
$allowext = $this->allowext;
if(!in_array($f_ext, $allowext)) {
throw new Exception('文件类型未被允许', 902);
}
//文件大小是否允许
$allowsize = $this->allowsize;
if($f_size > $allowsize) {
throw new Exception('文件超过允许的大小', 903);
}
//文件是否是上传的文件
if(!is_uploaded_file($f_tmpname)) {
throw new Exception('非上传的文件', 904);
}
//文件重命名 按时间命名 方便查看
if(empty($newname) && $auto_rename)
$new_name = $this->setFileNameByDate().'.'.$f_ext;
elseif(!empty($newname))
$new_name = $newname.'.'.$f_ext;
else
$new_name = $f_name;
//保存文件
$f_path = $savepath.$new_name;
if(move_uploaded_file($f_tmpname, $f_path)){
return $new_name;//上传成功,返回文件名。
}else{
throw new Exception('文件写入失败,请检查上传目录是否可写', 905);
}
}
//生成一个日期命名的文件名
private function setFileNameByDate(){
return date('YmdHis').rand(1000,9999);
}
完成了上传文件的功能接下来就要对这个文件进行压缩处理了。在这里用到了在脚本之家学习到的方法,做了一些改变。
function resizeImage($im, $dest, $maxwidth, $maxheight) {
$img = getimagesize($im);
switch ($img[2]) {
case 1:
$im = @imagecreatefromgif($im);
break;
case 2:
$im = @imagecreatefromjpeg($im);
break;
case 3:
$im = @imagecreatefrompng($im);
break;
}
$pic_width = imagesx($im);
$pic_height = imagesy($im);
$resizewidth_tag = false;
$resizeheight_tag = false;
if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
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);
imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
} else {
$newim = imagecreate($newwidth, $newheight);
imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
}
imagejpeg($newim, $dest);
imagedestroy($newim);
} else {
imagejpeg($im, $dest);
}
}
function getThumb($public_path,$sFile,$iWidth,$iHeight){
//图片公共路径 $public_path 这里改为有外部传入 根据具体情况进行修改
//判断该图片是否存在
if(!file_exists($public_path.$sFile)) return $sFile;
//判断图片格式(图片文件后缀)
$extend = explode("." , $sFile);
$attach_fileext = strtolower($extend[count($extend) - 1]);
if (!in_array($attach_fileext, array('jpg','png','jpeg'))){
return '';
}
//压缩图片文件名称
$sFileNameS = str_replace(".".$attach_fileext, "_".$iWidth.'_'.$iHeight.'.'.$attach_fileext, $sFile);
//判断是否已压缩图片,若是则返回压缩图片路径
if(file_exists($public_path.$sFileNameS)){
return $sFileNameS;
}
//生成压缩图片,并存储到原图同路径下
self::resizeImage($public_path.$sFile, $public_path.$sFileNameS, $iWidth, $iHeight);
if(!file_exists($public_path.$sFileNameS)){
return $sFile;
}
return $sFileNameS;
}
这样上传的图片就按给定的width、height按相同比例压缩 这里resizeImage指定了最大的宽,高也可根据实际需求情况去调整。
转载于:https://www.cnblogs.com/cyworz/p/10565211.html
php 实现图片上传并压缩功能相关推荐
- php微信小程序多图上传,tp5实现微信小程序多图片上传到服务器功能
最近在做一个教育类的小商城的微信小程序,用到了上传多个图片文件到服务器端,这里做一个讲解,希望对大家有所帮助. 1,小程序端: 在wxml文件中: 删除 点击上传作业 在js文件中: Page({ / ...
- JAVA实现一个图片上传预览功能
这个小项目主要使用java实现了一个简单的图片上传预览功能,废话不多说,先上实现成果 ^ _ ^
- java多图片上传插件,Bootstrap中的fileinput 多图片上传及编辑功能
Bootstrap中的fileinput 多图片上传及编辑功能 2019-01-01 编程之家收集整理的这篇文章主要介绍了Bootstrap中的fileinput 多图片上传及编辑功能,编程之家小编觉 ...
- js实现图片上传预览功能
js实现图片上传预览功能 很多业务场景下,我们需要在用户上传图片前,先预览待上传的图片 <body><input type="file"><img s ...
- vue+element实现图片上传及裁剪功能(vue-cropper)
需求背景: 上传图片或者头像时,能够将图片进行裁剪(等比例缩放裁剪或非等比例裁剪) 效果图: 安装使用 1.安装 npm install vue-cropper // npm 安装 yarn add ...
- vue图片上传及压缩组件的封装
vue图片上传及压缩组件的封装 源码地址 使用方法: 先去上面的链接把组件,复制到自己的components文件夹内 1.先下载 cnpm install compressorjs --save-de ...
- 微信JS图片上传与下载功能--微信JS系列文章(三)
概述 在前面的文章微信JS初始化-- 微信JS系列文章(一)中已经介绍了微信JS初始化的相关工作,接下来本文继续就微信JS的图片上传功能进行描述,供大家参考. 图片上传 $(function(){va ...
- js图片上传预览功能
最近项目中用到的图片上传前预览功能,兼容IE6-9,FF <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN&q ...
- SSM项目/SpringBoot项目/SpringBoot+Vue前后端分离项目 图片上传并查看功能实现汇总
SSM项目下的图片上传: 1.前端Js代码:用户点击"上传头像"按钮后,会执行uploadPhoto()的方法. <button type="button" ...
最新文章
- 近900000条if-then关系图谱,让神经网络“懂”常识推理
- VMware虚拟机打开后不兼容
- UGUI_忽略UI被拦截事件
- golang获取结构体中的tag_26. Go 语言中结构体的 Tag 用法
- Spark_UDAF
- Windows Azure Azure 简介
- 14 递归 匿名函数 内置函数
- Yii框架官方教程增补篇3——开始:创建第一个Yii应用
- MySql添加外键报错:Cannot add foreign key constraint
- 嵌入式linux软件/驱动开发工程师需要哪些知识
- TypeScript瞎看看
- java jersey,java Jersey
- 基于深度卷积神经网络的图像超分辨率重建(SRCNN) 学习笔记
- 如何使用真机测试运行HarmonyOS应用
- CSS:三种背景(斑马线,棋盘,格子)
- C语言中的if、else if 的用法和区别
- WINDOWS XP中使用DOS命令查看分区的格式
- APP推广助手,自动邀请码技术分享
- 用计算机画小鸡,水墨电脑画--丝瓜小鸡图
- 癫狂的dom——利用css3让dom动起来
热门文章
- mysql配置环境变量(win 10)_mysql配置环境变量(win 10)
- STM32项目(七) —— 智能仓库管理系统
- 模块化加载_谈谈双亲委派模型的第四次破坏-模块化
- Mybatis执行流程分析_自定义简易Mybatis框架
- 三、Vue组件化开发学习笔记——组件化的基本步骤、全局组件和局部组件、父组件和子组件、注册组件的语法糖、模板分离写法、组件的数据存放
- LeetCode 2032. 至少在两个数组中出现的值(哈希/位运算)
- LeetCode 995. K 连续位的最小翻转次数(差分思想)
- LeetCode 469. 凸多边形(向量叉积)
- LeetCode 390. 消除游戏(类似约瑟夫环,找映射规律)
- 程序员面试金典 - 面试题 16.07. 最大数值(位运算求max)