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 相关文章推荐
社区(php&amp;&amp;mysql)一
Oct 09 PHP
PHP 分页原理分析,大家可以看看
Dec 21 PHP
web目录下不应该存在多余的程序(安全考虑)
May 09 PHP
使用迭代器 遍历文件信息的详解
Jun 08 PHP
php实现Mongodb自定义方式生成自增ID的方法
Mar 23 PHP
护卫神php套件 php版本升级方法(php5.5.24)
May 10 PHP
php将远程图片保存到本地服务器的实现代码
Aug 03 PHP
PHP单链表的实现代码
Jul 05 PHP
Yii列表定义与使用分页方法小结(3种方法)
Jul 15 PHP
利用phpexcel对数据库数据的导入excel(excel筛选)、导出excel
Apr 27 PHP
CodeIgniter框架实现的整合Smarty引擎DEMO示例
Mar 28 PHP
PHP+Oracle本地开发环境搭建方法详解
Apr 01 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
德劲1107的电路分析与打磨
2021/03/02 无线电
PHP中批量生成静态html(命令行下运行PHP)
2014/04/19 PHP
php实现按指定大小等比缩放生成上传图片缩略图的方法
2014/12/15 PHP
Laravel框架分页实现方法分析
2018/06/12 PHP
使用onbeforeunload属性后的副作用
2007/03/08 Javascript
离开页面时检测表单元素是否被修改,提示保存的js代码
2010/08/25 Javascript
关于jQuery中的end()使用方法
2011/07/10 Javascript
实现前后端数据交互方法汇总
2015/04/07 Javascript
Vue 中批量下载文件并打包的示例代码
2017/11/20 Javascript
vue的diff算法知识点总结
2018/03/29 Javascript
Django+vue跨域问题解决的详细步骤
2019/01/20 Javascript
vue实现中部导航栏布局功能
2019/07/30 Javascript
JavaScript类的继承多种实现方法
2020/05/30 Javascript
[02:39]DOTA2英雄基础教程 极限穿梭编织者
2013/12/05 DOTA
[00:48]完美“圣”典2016风云人物:xiao8宣传片
2016/11/30 DOTA
[01:35:13]DOTA2-DPC中国联赛 正赛 DLG vs PHOENIX BO3 第一场 1月18日
2021/03/11 DOTA
python的正则表达式re模块的常用方法
2013/03/09 Python
分享Python字符串关键点
2015/12/13 Python
pandas获取groupby分组里最大值所在的行方法
2018/04/20 Python
Python JSON格式数据的提取和保存的实现
2019/03/22 Python
OpenCV搞定腾讯滑块验证码的实现代码
2019/05/18 Python
Ubuntu18.04中Python2.7与Python3.6环境切换
2019/06/14 Python
python求最大值最小值方法总结
2019/06/25 Python
用python写一个带有gui界面的密码生成器
2020/11/06 Python
解决pytorch 的state_dict()拷贝问题
2021/03/03 Python
css3 column实现卡片瀑布流布局的示例代码
2018/06/22 HTML / CSS
安德玛加拿大官网:Under Armour加拿大
2019/10/02 全球购物
优秀大学生的自我评价
2014/01/16 职场文书
学校十一活动方案
2014/02/01 职场文书
审计专业自荐信范文
2014/04/21 职场文书
学生会感恩节活动方案
2014/10/11 职场文书
商业门面租房协议书
2014/11/25 职场文书
股权转让协议书
2014/12/07 职场文书
导游词之西递宏村
2019/12/10 职场文书
Go缓冲channel和非缓冲channel的区别说明
2021/04/25 Golang
如何使JavaScript休眠或等待
2021/04/27 Javascript