PHP实现图片上传并压缩


Posted in PHP onDecember 22, 2015

本文实例讲解了PHP图片上传并压缩的实现方法,分享给大家供大家参考,具体内容如下

使用到三个文件

  • connect.php:连接数据库
  • test_upload.php:执行SQL语句
  • upload_img.php:上传图片并压缩

三个文件代码如下:
连接数据库:connect.php

<?php
$db_host = '';
$db_user = '';
$db_psw = '';
$db_name = '';
$db_port = '';
$sqlconn=new mysqli($db_host,$db_user,$db_psw,$db_name);
$q="set names utf8;";
$result=$sqlconn->query($q);
if (mysqli_connect_errno()) {
 printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
}
?>

执行SQL语句:test_upload.php

<?php
require ("connect.php");
require ("upload_img.php");
$real_img=$uploadfile; 
$small_img=$uploadfile_resize;
$insert_sql = "insert into img (real_img,small_img) values (?,?)";
$result = $sqlconn -> prepare($insert_sql);
$result -> bind_param("ss", $real_img,$small_img);
$result -> execute();
?>

上传图片并压缩upload_img.php

<?php 
//设置文件保存目录
$uploaddir = "upfiles/"; 
//设置允许上传文件的类型
$type=array("jpg","gif","bmp","jpeg","png"); 

//获取文件后缀名函数 
function fileext($filename) 
{ 
 return substr(strrchr($filename, '.'), 1); 
} 

//生成随机文件名函数 
function random($length) 
{ 
 $hash = 'CR-'; 
 $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; 
 $max = strlen($chars) - 1; 
 mt_srand((double)microtime() * 1000000); 
 for($i = 0; $i < $length; $i++) 
 { 
  $hash .= $chars[mt_rand(0, $max)]; 
 } 
 return $hash; 
} 

$a=strtolower(fileext($_FILES['filename']['name'])); 

//判断文件类型 
if(!in_array(strtolower(fileext($_FILES['filename']['name'])),$type)) 
{ 
 $text=implode(",",$type); 
 $ret_code=3;//文件类型错误
 $page_result=$text;
 $retArray = array('ret_code' => $ret_code,'page_result'=>$page_result);
 $retJson = json_encode($retArray);
 echo $retJson;
 return;
} 

//生成目标文件的文件名 
else
{ 
 $filename=explode(".",$_FILES['filename']['name']); 
 do 
 { 
  $filename[0]=random(10); //设置随机数长度 
  $name=implode(".",$filename); 
  //$name1=$name.".Mcncc"; 
  $uploadfile=$uploaddir.$name; 
 } 

 while(file_exists($uploadfile)); 

 if (move_uploaded_file($_FILES['filename']['tmp_name'],$uploadfile)) 
 { 
  if(is_uploaded_file($_FILES['filename']['tmp_name'])) 
  {
   $ret_code=1;//上传失败
  } 
 else 
 {//上传成功
  $ret_code=0;
 } 
 } 
$retArray = array('ret_code' => $ret_code);
$retJson = json_encode($retArray);
echo $retJson;
}

//压缩图片

$uploaddir_resize="upfiles_resize/";
$uploadfile_resize=$uploaddir_resize.$name;

//$pic_width_max=120;
//$pic_height_max=90;
//以上与下面段注释可以联合使用,可以使图片根据计算出来的比例压缩

$file_type=$_FILES["filename"]['type'];

function ResizeImage($uploadfile,$maxwidth,$maxheight,$name)
{
 //取得当前图片大小
 $width = imagesx($uploadfile);
 $height = imagesy($uploadfile);
 $i=0.5;
 //生成缩略图的大小
 if(($width > $maxwidth) || ($height > $maxheight))
 {
  /*
  $widthratio = $maxwidth/$width;
  $heightratio = $maxheight/$height;
  
  if($widthratio < $heightratio)
  {
   $ratio = $widthratio;
  }
  else
  {
    $ratio = $heightratio;
  }
  
  $newwidth = $width * $ratio;
  $newheight = $height * $ratio;
  */
  $newwidth = $width * $i;
  $newheight = $height * $i;
  if(function_exists("imagecopyresampled"))
  {
   $uploaddir_resize = imagecreatetruecolor($newwidth, $newheight);
   imagecopyresampled($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  }
  else
  {
   $uploaddir_resize = imagecreate($newwidth, $newheight);
   imagecopyresized($uploaddir_resize, $uploadfile, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
  }
  
  ImageJpeg ($uploaddir_resize,$name);
  ImageDestroy ($uploaddir_resize);
 }
 else
 {
  ImageJpeg ($uploadfile,$name);
 }
}



if($_FILES["filename"]['size'])
{
 if($file_type == "image/pjpeg"||$file_type == "image/jpg"|$file_type == "image/jpeg")
 {
  //$im = imagecreatefromjpeg($_FILES[$upload_input_name]['tmp_name']);
  $im = imagecreatefromjpeg($uploadfile);
 }
 elseif($file_type == "image/x-png")
 {
  //$im = imagecreatefrompng($_FILES[$upload_input_name]['tmp_name']);
  $im = imagecreatefromjpeg($uploadfile);
 }
 elseif($file_type == "image/gif")
 {
  //$im = imagecreatefromgif($_FILES[$upload_input_name]['tmp_name']);
  $im = imagecreatefromjpeg($uploadfile);
 }
 else//默认jpg
 {
  $im = imagecreatefromjpeg($uploadfile);
 }
 if($im)
 {
  ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize);
 
  ImageDestroy ($im);
 }
} 
?>

请按照现实情况更改connect.php,test_upload.php中对应的信息。

以上就是PHP实现图片上传并压缩的方法,希望对大家的学习php程序设计有所帮助

PHP 相关文章推荐
提取HTML标签
Oct 09 PHP
消息持续发送的完整例子
Oct 09 PHP
PHP4和PHP5性能测试和对比 测试代码与环境
Aug 17 PHP
PHP 数据库树的遍历方法
Feb 06 PHP
php实现12306余票查询、价格查询示例
Apr 17 PHP
codeigniter框架The URI you submitted has disallowed characters错误解决方法
May 06 PHP
php导出csv格式数据并将数字转换成文本的思路以及代码分享
Jun 05 PHP
ThinkPHP3.1的Widget新用法
Jun 19 PHP
ThinkPHP 表单自动验证运用示例
Oct 13 PHP
详解WordPress中创建和添加过滤器的相关PHP函数
Dec 29 PHP
php连接oracle数据库的核心步骤
May 26 PHP
如何用RabbitMQ和Swoole实现一个异步任务系统
May 29 PHP
Linux系统中设置多版本PHP共存配合Nginx服务器使用
Dec 21 #PHP
在Mac OS上搭建Nginx+PHP+MySQL开发环境的教程
Dec 21 #PHP
Linux下从零开始安装配置Nginx服务器+PHP开发环境
Dec 21 #PHP
反射调用private方法实践(php、java)
Dec 21 #PHP
关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题
Dec 21 #PHP
变量在 PHP7 内部的实现(二)
Dec 21 #PHP
变量在 PHP7 内部的实现(一)
Dec 21 #PHP
You might like
PHP无限分类代码,支持数组格式化、直接输出菜单两种方式
2011/05/18 PHP
php抓取页面的几种方法详解
2013/06/17 PHP
CodeIgniter实现更改view文件夹路径的方法
2014/07/04 PHP
php的4种常用运行方式详解
2016/12/22 PHP
PHP实现链式操作的三种方法详解
2017/11/16 PHP
PHP mongodb操作类定义与用法示例【适合mongodb2.x和mongodb3.x】
2018/06/16 PHP
range 标准化之获取
2011/08/28 Javascript
js跳转页面方法实现汇总
2014/02/11 Javascript
jquery动态调整div大小使其宽度始终为浏览器宽度
2014/06/06 Javascript
针对初学者的jQuery入门指南
2015/08/15 Javascript
Vue-cli proxyTable 解决开发环境的跨域问题详解
2017/05/18 Javascript
使用jquery的jsonp如何发起跨域请求及其原理详解
2017/08/17 jQuery
JavaScript实现移动端页面按手机屏幕分辨率自动缩放的最强代码
2017/08/18 Javascript
理解javascript async的用法
2017/08/22 Javascript
Angularjs 1.3 中的$parse实例代码
2017/09/14 Javascript
angular json对象push到数组中的方法
2018/02/27 Javascript
React中使用UMEditor的方法示例
2019/12/27 Javascript
[03:16]DOTA2完美大师赛主赛事首日集锦
2017/11/23 DOTA
Python cookbook(数据结构与算法)根据字段将记录分组操作示例
2018/03/19 Python
对python中raw_input()和input()的用法详解
2018/04/22 Python
Python爬虫抓取代理IP并检验可用性的实例
2018/05/07 Python
Django实现表单验证
2018/09/08 Python
python实现给微信指定好友定时发送消息
2019/04/29 Python
pip安装python库的方法总结
2019/08/02 Python
python实现超市管理系统(后台管理)
2019/10/25 Python
Python3操作读写CSV文件使用包过程解析
2020/04/10 Python
基于Python中random.sample()的替代方案
2020/05/23 Python
Gap工厂店:Gap Factory
2017/11/02 全球购物
办理居住证介绍信
2014/01/15 职场文书
终止劳动合同证明书样本
2014/11/19 职场文书
小学教师个人工作总结2015
2015/04/20 职场文书
2015年机关纠风工作总结
2015/05/15 职场文书
2015年电气技术员工作总结
2015/07/24 职场文书
教学副校长工作总结
2015/08/13 职场文书
使用numpy nonzero 找出非0元素
2021/05/14 Python
Python通过loop.run_in_executor执行同步代码 同步变为异步
2022/04/11 Python