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 相关文章推荐
一个连接两个不同MYSQL数据库的PHP程序
Oct 09 PHP
php 文章调用类代码
Aug 11 PHP
openPNE常用方法分享
Nov 29 PHP
深入PHP获取随机数字和字母的方法详解
Jun 06 PHP
使用PHP生成二维码的两种方法(带logo图像)
Mar 14 PHP
探寻PHP脚本不报错的原因
Jun 12 PHP
让codeigniter与swfupload整合的最佳解决方案
Jun 12 PHP
Thinkphp调用Image类生成缩略图的方法
Mar 07 PHP
CI框架实现框架前后端分离的方法详解
Dec 30 PHP
PHP实现的AES双向加密解密功能示例【128位】
Sep 03 PHP
ThinkPHP框架下微信支付功能总结踩坑笔记
Apr 10 PHP
PHP+redis实现的限制抢购防止商品超发功能详解
Sep 19 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实现递归循环每一个目录
2010/08/08 PHP
centos 7.2下搭建LNMP环境教程
2016/11/20 PHP
Yii框架弹出窗口组件CJuiDialog用法分析
2017/01/07 PHP
PHP在同一域名下两个不同的项目做独立登录机制详解
2017/09/22 PHP
php 中htmlentities导致中文无法查询问题
2018/09/10 PHP
jquery 事件执行检测代码
2009/12/09 Javascript
js中取得变量绝对值的方法
2015/01/03 Javascript
jqPlot jQuery绘图插件的使用
2016/06/18 Javascript
js判断是否为空和typeof的用法(详解)
2016/10/07 Javascript
js入门之Function函数的使用方法【新手必看】
2016/11/22 Javascript
基于Vue实例生命周期(全面解析)
2017/08/16 Javascript
详解vue页面首次加载缓慢原因及解决方案
2019/11/06 Javascript
vue ajax 拦截原理与实现方法示例
2019/11/29 Javascript
jQuery实现全选、反选和不选功能的方法详解
2019/12/04 jQuery
vue 监听 Treeselect 选择项的改变操作
2020/08/31 Javascript
Python协程的用法和例子详解
2017/09/09 Python
python导入csv文件出现SyntaxError问题分析
2017/12/15 Python
Flask框架Flask-Principal基本用法实例分析
2018/07/23 Python
Python3实现的判断环形链表算法示例
2019/03/07 Python
Python动态语言与鸭子类型详解
2019/07/01 Python
python实现LBP方法提取图像纹理特征实现分类的步骤
2019/07/11 Python
python 实现方阵的对角线遍历示例
2019/11/29 Python
PyQt5实现画布小程序
2020/05/30 Python
美国知名的女性服饰品牌:LOFT(洛芙特)
2016/08/05 全球购物
加拿大健康、婴儿和美容产品在线购物:Well.ca
2016/11/30 全球购物
JVM是一个编译程序还是解释程序
2012/09/11 面试题
外语系毕业生自荐信范文
2013/12/16 职场文书
给客户的道歉信
2014/01/13 职场文书
医院检讨书范文
2014/02/01 职场文书
公司采购主管岗位职责
2014/06/17 职场文书
医药销售自我评价200字
2014/09/11 职场文书
民主评议政风行风活动心得体会
2014/10/29 职场文书
幽灵公主观后感
2015/06/09 职场文书
机关干部纪律作风整顿心得体会
2016/01/23 职场文书
Ajax 的初步实现(使用vscode+node.js+express框架)
2021/06/18 Javascript
SQL Server 中的事务介绍
2022/05/20 SQL Server