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 相关文章推荐
同时提取多条新闻中的文本一例
Oct 09 PHP
PHP 函数语法介绍一
Jun 14 PHP
php获取用户IPv4或IPv6地址的代码
Nov 15 PHP
Android ProgressBar进度条和ProgressDialog进度框的展示DEMO
Jun 19 PHP
php生成固定长度纯数字编码的方法
Jul 09 PHP
YII Framework框架教程之日志用法详解
Mar 14 PHP
PHP编写简单的App接口
Aug 28 PHP
PHP实现根据密码长度显示安全条
Jul 04 PHP
PHP 进度条函数的简单实例
Sep 19 PHP
PHP中遍历数组的三种常用方法实例分析
Jun 24 PHP
Laravel5.1 框架Middleware中间件基本用法实例分析
Jan 04 PHP
php设计模式之职责链模式实例分析【星际争霸游戏案例】
Mar 27 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(1)
2006/10/09 PHP
PHP生成静态页
2006/11/25 PHP
PHP JSON格式数据交互实例代码详解
2011/01/13 PHP
php 流程控制switch的简单实例
2016/06/07 PHP
快速解决FusionCharts联动的中文乱码问题
2013/12/04 Javascript
NODE.JS加密模块CRYPTO常用方法介绍
2014/06/05 Javascript
jquery和js实现对div的隐藏和显示方法
2014/09/26 Javascript
Javascript 多物体运动的实现
2014/12/24 Javascript
浏览器兼容性问题大汇总
2015/12/17 Javascript
基于bootstrop常用类总结(推荐)
2017/09/11 Javascript
js实现鼠标移动到图片产生遮罩效果
2017/10/21 Javascript
vue.js绑定事件监听器示例【基于v-on事件绑定】
2018/07/07 Javascript
解决angularjs WdatePicker ng-model的问题
2018/09/13 Javascript
vue-cli 使用vue-bus来全局控制的实例讲解
2018/09/15 Javascript
一步一步的了解webpack4的splitChunk插件(小结)
2018/09/17 Javascript
JS实现查找数组中对象的属性值是否存在示例
2019/05/24 Javascript
vue使用video插件vue-video-player详解
2020/10/23 Javascript
Python切片用法实例教程
2014/09/08 Python
python使用分治法实现求解最大值的方法
2015/05/12 Python
Django 如何获取前端发送的头文件详解(推荐)
2017/08/15 Python
Python实现基本数据结构中队列的操作方法示例
2017/12/04 Python
用Python实现筛选文件脚本的方法
2018/10/27 Python
如何在Django配置文件里配置session链接
2019/08/06 Python
Python通过VGG16模型实现图像风格转换操作详解
2020/01/16 Python
tensorflow estimator 使用hook实现finetune方式
2020/01/21 Python
python如何通过twisted搭建socket服务
2020/02/03 Python
python GUI库图形界面开发之PyQt5表格控件QTableView详细使用方法与实例
2020/03/01 Python
appium+python adb常用命令分享
2020/03/06 Python
英国最红的高街时尚品牌:Topshop
2016/08/05 全球购物
采购主管工作职责
2013/12/12 职场文书
合作意向书模板
2014/03/31 职场文书
公路绿化方案
2014/05/12 职场文书
歌舞青春观后感
2015/06/10 职场文书
python 破解加密zip文件的密码
2021/04/22 Python
Java常用工具类汇总 附示例代码
2021/06/26 Java/Android
详解MySQL中timestamp和datetime时区问题导致做DTS遇到的坑
2021/12/06 MySQL