search
HomeBackend DevelopmentPHP TutorialHow to use php to handle the compression function of multiple image uploads

This article mainly introduces the function of php processing multi-image upload compression code. It is very good and has certain reference value. Friends who need it can refer to it

I read some information online about processing image compression , most of the ones I found were single-image compression, either single front-end or back-end, so I adjusted the front-end and front-end compression myself, and supported multi-image compressed image instances. There is a lot of code, it will be clearer if you copy it directly to the editor

1. First create a simple upload page upload.php. First compress the image through the front-end code, and directly upload the code

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <title>实名验证</title>
  <script type="text/javascript">
    /*
    三个参数
    file:一个是文件(类型是图片格式),
    w:一个是文件压缩的后宽度,宽度越小,字节越小
    objp:一个是容器或者回调函数
    photoCompress()
     */
    function photoCompress(file,w,objp){
      var ready=new FileReader();
      /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
      ready.readAsDataURL(file);
      ready.onload=function(){
        var re=this.result;
        canvasDataURL(re,w,objp)
      }
    }
    function canvasDataURL(path, obj, callback){
      var img = new Image();
      img.src = path;
      img.onload = function(){
        var that = this;
        // 默认按比例压缩
        var w = that.width,
          h = that.height,
          scale = w / h;
        w = obj.width || w;
        h = obj.height || (w / scale);
        var quality = 0.7; // 默认图片质量为0.7
        //生成canvas
        var canvas = document.createElement(&#39;canvas&#39;);
        var ctx = canvas.getContext(&#39;2d&#39;);
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // 图像质量
        if(obj.quality && obj.quality <= 1 && obj.quality > 0){
          quality = obj.quality;
        }
        // quality值越小,所绘制出的图像越模糊
        var base64 = canvas.toDataURL(&#39;image/jpeg&#39;, quality);
        // 回调函数返回base64的值
        callback(base64);
      }
    }
    /**
     * 将以base64的图片url数据转换为Blob
     * @param urlData
     * 用url方式表示的base64图片数据
     */
    function convertBase64UrlToBlob(urlData){
      var arr = urlData.split(&#39;,&#39;), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {type:mime});
    }
    var xhr;
    //上传文件方法
    function uploadClick() {
      document.getElementsByClassName("uploadbtn")[0].value = &#39;上传中...&#39;;
      document.getElementsByClassName("uploadbtn")[0].disabled=true; 
      var obj = document.getElementsByClassName("myfile");
      for(var i=0;i<2;i++){
        UploadFile(obj[i].files[0],&#39;file&#39;+i);
      }
    }
    function UploadFile(fileObj,filed){
      var shopid = document.getElementById(&#39;shopid&#39;).value;
      var adminid = document.getElementById(&#39;adminid&#39;).value;
      var url = "newshimingupload.php"; // 接收上传文件的后台地址 
      var form = new FormData(); // FormData 对象
      if(fileObj.size/1024 > 100) { //大于100k,进行压缩上传
        photoCompress(fileObj, {
          quality: 0.2
        }, function(base64Codes){
          //console.log("压缩后:" + base.length / 1024 + " " + base);
          var bl = convertBase64UrlToBlob(base64Codes);
          form.append("file", bl, "file_"+Date.parse(new Date())+".jpg"); // 文件对象
          form.append("shopid", shopid); // 文件对象
          form.append("adminid", adminid); // 文件对象
          form.append("filed", filed); // 文件对象
          xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
          xhr.open("post", url, false); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
          xhr.onload = uploadComplete; //请求完成
          xhr.onerror = uploadFailed; //请求失败
          // xhr.upload.onprogress = progressFunction;//【上传进度调用方法实现】
          xhr.upload.onloadstart = function(){//上传开始执行方法
            ot = new Date().getTime();  //设置上传开始时间
            oloaded = 0;//设置上传开始时,以上传的文件大小为0
          };
          xhr.send(form); //开始上传,发送form数据
        });
      }else{ //小于等于1M 原图上传
        form.append("file", fileObj); // 文件对象
        form.append("shopid", shopid); // 文件对象
        form.append("adminid", adminid); // 文件对象
        form.append("filed", filed); // 文件对象
        xhr = new XMLHttpRequest(); // XMLHttpRequest 对象
        xhr.open("post", url, false); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
        xhr.onload = uploadComplete; //请求完成
        xhr.onerror = uploadFailed; //请求失败
        xhr.upload.onloadstart = function(){//上传开始执行方法
          ot = new Date().getTime();  //设置上传开始时间
          oloaded = 0;//设置上传开始时,以上传的文件大小为0
        };
        xhr.send(form); //开始上传,发送form数据
      }
    }
    //上传成功响应
    function uploadComplete(evt) {
      //服务断接收完文件返回的结果
      var data = JSON.parse(evt.target.responseText);
      console.log(data);
      if(data.status){
        alert(data.msg);
        if(data.msg == &#39;门店照上传成功&#39;){
          window.location.href = "/dd_admin/index.php";
        }
      }
    }
    //上传失败
    function uploadFailed(evt) {
      alert("网络不稳定,请重新上传!");
    }
  </script>
</head>
<body>
  <style type="text/css">
    .main{text-align: center;padding-top: 50px;}
    .main .myfile{margin-bottom: 15px;}
  </style>
<p class="main">
  营业执照:
  <input type="file" class="myfile" id="file1" name="file1" accept="image/x-png, image/jpg, image/jpeg, image/gif"/><br>
  门店照:
  <input type="file" class="myfile" id="file2" name="file2" accept="image/x-png, image/jpg, image/jpeg, image/gif"/><br>
  <input type="hidden" id="shopid" name="shopid" value="<?php echo $_GET[&#39;shopid&#39;]; ?>" maxlength="15">
  <input type="hidden" id="adminid" name="adminid" value="<?php echo $_GET[&#39;adminid&#39;]; ?>" maxlength="15">
  <input style="margin-top: 25px;" class="uploadbtn" type="button" onclick="uploadClick()" value="上传" /><br>
</p>
</body>
</html>
2、前端图片压缩后,请求到自定义的接口upload_deal.php.代码如下
<?php
require_once(&#39;public_func.php&#39;);
  actionUpload(&#39;uploads/&#39;,&#39;file&#39;); //参数分别代表图片存储的路径和上传的文件名
}
3、在第二部引入public_func.php,这块代码主要是对后端处理图片压缩
function actionUpload($path = &#39;/uploads/&#39;,$filename=&#39;myFile&#39;)
  {
    // $path = &#39;uploads/&#39;;  //图片存放根目录 根据自己项目路径而定
    $file = $_FILES[$filename][&#39;name&#39;];
    $folder = $path.date(&#39;Ymd&#39;)."/";
    $pre = rand(999,9999).time();
    $ext = strrchr($file,&#39;.&#39;);
    $newName = $pre.$ext;
    $out = array(
      &#39;msg&#39;=>&#39;&#39;,
      &#39;status&#39;=>&#39;error&#39;,
      &#39;img_url&#39;=>&#39;&#39;
    );
    if(!is_dir($folder))
    {
      if(!mkdir($folder, 0777, true)){
        $out[&#39;msg&#39;] = &#39;图片目录创建失败!&#39;;
        echo json_encode($out);
        exit;
      }
    }
    $im = $_FILES[$filename][&#39;tmp_name&#39;]; //上传图片资源
    $maxwidth="1056"; //设置图片的最大宽度
    $maxheight="500"; //设置图片的最大高度
    $imgname = $folder.$newName; //图片存放路径 根据自己图片路径而定
    $filetype=$_FILES[$filename][&#39;type&#39;];//图片类型
    $result = thumbImage($im,$maxwidth,$maxheight,$imgname,$filetype);
    if($result){
      $out[&#39;msg&#39;] = &#39;图片上传成功&#39;;
      $out[&#39;status&#39;] = &#39;success&#39;;
      $out[&#39;img_url&#39;] = $folder.$newName;
    }else{
      $out[&#39;msg&#39;] = &#39;图片上传失败&#39;;
    }
    return json_encode($out);
    exit;
  }
  //压缩图片
  function thumbImage($im,$maxwidth,$maxheight,$name,$filetype)
  {
    switch ($filetype) {   
      case &#39;image/pjpeg&#39;:   
      case &#39;image/jpeg&#39;:   
        $im = imagecreatefromjpeg($im);  //PHP图片处理系统函数
        break;   
      case &#39;image/gif&#39;:   
        $im = imagecreatefromgif($im);  
        break;   
      case &#39;image/png&#39;:   
        $im = imagecreatefrompng($im);  
        break;
      case &#39;image/wbmp&#39;:   
        $im = imagecreatefromwbmp($im);  
        break;       
    } 
    $resizewidth_tag = $resizeheight_tag = false;
    $pic_width = imagesx($im);
    $pic_height = imagesy($im);
    if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
    {
  $resizewidth_tag = $resizeheight_tag = false;
      if($maxwidth && $pic_width>$maxwidth)
      {
        $widthratio = $maxwidth / $pic_width;
        $resizewidth_tag = true;
      }
      if($maxheight && $pic_height>$maxheight)
      {
        $heightratio = $maxheight / $pic_height;
        $resizeheight_tag = true;
      }
      if($resizewidth_tag && $resizeheight_tag)
      {
        if($widthratio < $heightratio)
         $ratio = $widthratio;
        else
         $ratio = $heightratio;
      }
      if($resizewidth_tag && !$resizeheight_tag)
      $ratio = $widthratio;
      if($resizeheight_tag && !$resizewidth_tag)
      $ratio = $heightratio;
      $newwidth = $pic_width * $ratio;
      $newheight = $pic_height * $ratio;
      if(function_exists("imagecopyresampled"))
      {
        $newim = imagecreatetruecolor($newwidth,$newheight);//PHP图片处理系统函数
        imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP图片处理系统函数
      }
      else
      {
        $newim = imagecreate($newwidth,$newheight);
        imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
      }
      switch ($filetype) {   
        case &#39;image/pjpeg&#39; :   
        case &#39;image/jpeg&#39; :   
          $result = imagejpeg($newim,$name);  
          break;   
        case &#39;image/gif&#39; :   
          $result = imagegif($newim,$name);  
          break;   
        case &#39;image/png&#39; :   
          $result = imagepng($newim,$name);  
          break;
        case &#39;image/wbmp&#39; :   
          $result = imagewbmp($newim,$name);  
          break;       
      } 
      imagedestroy($newim);
    }
    else
    {
      switch ($filetype) {   
        case &#39;image/pjpeg&#39; :   
        case &#39;image/jpeg&#39; :   
          $result = imagejpeg($im,$name);  
          break;   
        case &#39;image/gif&#39; :   
          $result = imagegif($im,$name);  
          break;   
        case &#39;image/png&#39; :   
          $result = imagepng($im,$name);  
          break;
        case &#39;image/wbmp&#39; :   
          $result = imagewbmp($im,$name);  
          break;       
      }
    }
    return $result; 
  }

. The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please Follow PHP Chinese website!

Related recommendations:

How to generate promotional posters with PHP

##Use PHP to achieve the function of top articles

Code for exporting data and pictures using PHPEXCEL

The above is the detailed content of How to use php to handle the compression function of multiple image uploads. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Notifications in LaravelNotifications in LaravelMar 04, 2025 am 09:22 AM

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov

Explain the concept of late static binding in PHP.Explain the concept of late static binding in PHP.Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log AnalysisPHP Logging: Best Practices for PHP Log AnalysisMar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),