PHP实现图片上传并压缩

作者:lijiao 时间:2024-05-22 10:06:09 

本文实例讲解了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,图片上传,图片压缩
0
投稿

猜你喜欢

  • 详解JavaScript中的Object.is()与"==="运算符总结

    2024-04-22 12:50:25
  • SQL 随机查询 包括(sqlserver,mysql,access等)

    2024-01-26 15:42:43
  • 简析Oracle数据库常见问题及解决方案

    2024-01-24 11:15:01
  • ASP短日期格式为长日期

    2009-06-11 12:53:00
  • Python openpyxl读取单元格字体颜色过程解析

    2023-02-09 06:57:02
  • Python3使用 GitLab API 进行批量合并分支

    2023-05-26 08:38:53
  • 设计"以人为本"和"绿色设计"

    2008-10-07 12:21:00
  • golang 执行命令行的实现

    2024-04-28 09:14:40
  • 开发Web应用程序的结构化过程

    2009-06-01 10:52:00
  • mysql中find_in_set()函数的使用及in()用法详解

    2024-01-25 18:32:38
  • Python使用PDFMiner解析PDF代码实例

    2023-03-30 06:56:45
  • 基于GORM实现CreateOrUpdate方法详解

    2024-02-14 09:18:02
  • 4种JavaScript实现简单tab选项卡切换的方法

    2024-02-23 10:25:51
  • 解决Django layui {{}}冲突的问题

    2023-07-23 15:22:18
  • 如何使用python爬取知乎热榜Top50数据

    2021-11-13 05:47:09
  • 菜单效果

    2020-08-16 04:45:01
  • 图片链接轮换代码, 支持预载

    2007-10-16 19:57:00
  • asp测字符串长度及截取定长字符串汉字的处理

    2007-10-12 13:14:00
  • vue项目中的数据变化被watch监听并处理

    2024-04-27 16:11:53
  • sqlalchemy实现时间列自动更新教程

    2021-08-18 20:12:58
  • asp之家 网络编程 m.aspxhome.com