PHP实现图片上传并压缩

本文实例讲解了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中对应的信息。

转自:http://www.jb51.net/article/76763.htm

转载于:https://www.cnblogs.com/chengzhi59/p/7272195.html

你可以使用PHP的GD库来实现图片压缩,以下是一个简单的示例代码: ```php <?php // 获取上传文件 $file = $_FILES['image']; // 定义压缩后的宽度和高度 $newWidth = 800; $newHeight = 600; // 创建一个空白的画布,大小为压缩后的尺寸 $canvas = imagecreatetruecolor($newWidth, $newHeight); // 从上传文件中创建一个图像对象 $source = imagecreatefromjpeg($file['tmp_name']); // 获取上传文件的原始尺寸 $width = imagesx($source); $height = imagesy($source); // 计算压缩比例 $scaleX = $newWidth / $width; $scaleY = $newHeight / $height; $scale = min($scaleX, $scaleY); // 计算压缩后的新尺寸 $newWidth = round($scale * $width); $newHeight = round($scale * $height); // 将上传文件缩放并复制到画布上 imagecopyresampled($canvas, $source, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); // 将压缩后的图像保存到文件 imagejpeg($canvas, 'compressed_image.jpg', 80); // 释放资源 imagedestroy($source); imagedestroy($canvas); ?> ``` 上述代码中,我们首先获取上传的文件,然后创建一个空白的画布,大小为压缩后的尺寸。接着,我们从上传文件中创建一个图像对象,并获取上传文件的原始尺寸。然后,我们计算压缩比例,并计算压缩后的新尺寸。最后,我们将上传文件缩放并复制到画布上,并将压缩后的图像保存到文件。 请注意,以上代码中使用的是JPEG格式,如果你上传的是其他格式的图片,需要根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值