SoFunction
Updated on 2025-03-09

PHP implements image upload and compression

This article explains the implementation method of uploading and compressing PHP images, and is shared with you for your reference. The specific content is as follows

Use three files

  • : Connect to the database
  • test_upload.php: Execute SQL statement
  • upload_img.php: upload image and compress

The three file codes are as follows:
Connect to the database:

<?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();
}
?>

Execute SQL statements:test_upload.php

<?php
require ("");
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 the picture and compress itupload_img.php

&lt;?php 
//Set the file save directory$uploaddir = "upfiles/"; 
//Set the type that allows uploading of files$type=array("jpg","gif","bmp","jpeg","png"); 

//Get the file suffix name functionfunction fileext($filename) 
{ 
 return substr(strrchr($filename, '.'), 1); 
} 

//Generate random file name functionfunction random($length) 
{ 
 $hash = 'CR-'; 
 $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz'; 
 $max = strlen($chars) - 1; 
 mt_srand((double)microtime() * 1000000); 
 for($i = 0; $i &lt; $length; $i++) 
 { 
  $hash .= $chars[mt_rand(0, $max)]; 
 } 
 return $hash; 
} 

$a=strtolower(fileext($_FILES['filename']['name'])); 

//Judge file typeif(!in_array(strtolower(fileext($_FILES['filename']['name'])),$type)) 
{ 
 $text=implode(",",$type); 
 $ret_code=3;//File type error $page_result=$text;
 $retArray = array('ret_code' =&gt; $ret_code,'page_result'=&gt;$page_result);
 $retJson = json_encode($retArray);
 echo $retJson;
 return;
} 

//The file name of the generated target fileelse
{ 
 $filename=explode(".",$_FILES['filename']['name']); 
 do 
 { 
  $filename[0]=random(10); //Set the random number length  $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;//Upload failed  } 
 else 
 {//Upload successfully  $ret_code=0;
 } 
 } 
$retArray = array('ret_code' =&gt; $ret_code);
$retJson = json_encode($retArray);
echo $retJson;
}

//Compress the picture
$uploaddir_resize="upfiles_resize/";
$uploadfile_resize=$uploaddir_resize.$name;

//$pic_width_max=120;
//$pic_height_max=90;
//The above and the following comments can be used in combination to make the picture compressed according to the calculated proportions
$file_type=$_FILES["filename"]['type'];

function ResizeImage($uploadfile,$maxwidth,$maxheight,$name)
{
 //Get the current image size $width = imagesx($uploadfile);
 $height = imagesy($uploadfile);
 $i=0.5;
 //The size of the generated thumbnail if(($width &gt; $maxwidth) || ($height &gt; $maxheight))
 {
  /*
  $widthratio = $maxwidth/$width;
  $heightratio = $maxheight/$height;
  
  if($widthratio &lt; $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//Default jpg {
  $im = imagecreatefromjpeg($uploadfile);
 }
 if($im)
 {
  ResizeImage($im,$pic_width_max,$pic_height_max,$uploadfile_resize);
 
  ImageDestroy ($im);
 }
} 
?&gt;

Please change the corresponding information in test_upload.php according to the actual situation.

The above is the method of uploading and compressing images by PHP. I hope it will be helpful for everyone to learn PHP programming.