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初学入门
Nov 19 PHP
apache rewrite_module模块使用教程
Jan 10 PHP
了解Joomla 这款来自国外的php网站管理系统
Mar 11 PHP
php pthreads多线程的安装与使用
Jan 19 PHP
php htmlentities()函数的定义和用法
May 13 PHP
php在windows环境下获得cpu内存实时使用率(推荐)
Feb 08 PHP
php使用curl获取header检测开启GZip压缩的方法
Aug 15 PHP
PHP删除字符串中非字母数字字符方法总结
Jan 20 PHP
PHP asXML()函数讲解
Feb 03 PHP
php的无刷新操作实现方法分析
Feb 28 PHP
PHP ob缓存以及ob函数原理实例解析
Nov 13 PHP
TP5多入口设置实例讲解
Dec 15 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
德生S2000南麂列岛台湾FM收听记录
2021/03/02 无线电
php下获取客户端ip地址的函数
2010/03/15 PHP
php中flush()、ob_flush()、ob_end_flush()的区别介绍
2013/02/17 PHP
微信支付PHP SDK之微信公众号支付代码详解
2015/12/09 PHP
[原创]图片分页查看
2006/08/28 Javascript
Javascript实例教程(19) 使用HoTMetal(5)
2006/12/23 Javascript
jQuery 各种浏览器下获得日期区别
2008/12/22 Javascript
跟我学习javascript创建对象(类)的8种方法
2015/11/20 Javascript
jQuery中text() val()和html()的区别实例详解
2016/06/28 Javascript
微信小程序  wx.request合法域名配置详解
2016/11/23 Javascript
jQuery实现字符串全部替换的方法
2016/12/12 Javascript
js限制输入框只能输入数字(onkeyup触发)
2018/09/28 Javascript
在Vant的基础上封装下拉日期控件的代码示例
2018/12/05 Javascript
用JS实现选项卡
2020/03/23 Javascript
Vue全局使用less样式,组件使用全局样式文件中定义的变量操作
2020/10/21 Javascript
[00:58]PWL开团时刻DAY5——十人开雾0换5
2020/11/04 DOTA
python基础教程之lambda表达式使用方法
2014/02/12 Python
python使用锁访问共享变量实例解析
2018/02/08 Python
windows下搭建python scrapy爬虫框架步骤
2018/12/23 Python
用Python实现校园通知更新提醒功能
2019/11/23 Python
django Layui界面点击弹出对话框并请求逻辑生成分页的动态表格实例
2020/05/12 Python
利用OpenCV中对图像数据进行64F和8U转换的方式
2020/06/03 Python
python实现AHP算法的方法实例(层次分析法)
2020/09/09 Python
eDreams澳大利亚:预订机票、酒店和度假产品
2017/04/19 全球购物
资生堂英国官网:Shiseido英国
2020/12/30 全球购物
请写出 BOOL flag 与"零值"比较的 if 语句
2016/02/29 面试题
售房委托书
2014/08/30 职场文书
党员批评与自我批评发言稿
2014/10/14 职场文书
高中班主任评语
2014/12/30 职场文书
2015年禁毒宣传活动总结
2015/03/25 职场文书
关于运动会的宣传稿
2015/07/23 职场文书
新兵入伍决心书
2015/09/22 职场文书
创业计划书之网络外卖
2019/10/31 职场文书
导游词之蓬莱长岛
2019/12/17 职场文书
python实现ROA算子边缘检测算法
2021/04/05 Python
golang定时器
2022/04/14 Golang