溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么通過js實(shí)現(xiàn)壓縮圖片上傳功能

發(fā)布時(shí)間:2021-04-19 09:52:25 來源:億速云 閱讀:221 作者:小新 欄目:web開發(fā)

這篇文章給大家分享的是有關(guān)怎么通過js實(shí)現(xiàn)壓縮圖片上傳功能的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

大概的流程就是

  • 點(diǎn)擊file選擇圖片

  • js將圖片解讀出base64編碼,然后通過js將base64編碼轉(zhuǎn)為壓縮后的base64

  • 然后通過ajax或者form把壓縮后的base64編碼提交到服務(wù)器(php)

  • 然后php將base64寫入文件

html

<!-- 首先引入jquery!!!!!!這里沒有引入 -->


<img src="/Uploads/verifyinfo/cardz.png" >
<input id="cardz" name="cardz" class="weui-uploader__input" type="file" accept="image/*" multiple="">
<input type="hidden" id="cardzbase" name="cardzbase">


<script>
 $(function(){
  $("input[type=file]").on('change', function(){

   var filePath = $(this).val(),     //獲取到input的value,里面是文件的路徑
       fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
       fileObj = document.getElementById($(this).attr('id')).files[0]; //上傳文件的對象,要這樣寫才行,用jquery寫法獲取不到對象

   var imgBase64str = '';   //存儲(chǔ)圖片的imgBase64
   // 檢查是否是圖片
   if( !fileFormat.match(/.png|.jpg|.jpeg/) ) {
    alert('上傳錯(cuò)誤,文件格式必須為:png/jpg/jpeg');
    return;
   }
   var that = this;
   // 調(diào)用函數(shù),對圖片進(jìn)行壓縮
   compress(fileObj,function(imgBase64){
    imgBase64str = imgBase64;//存儲(chǔ)轉(zhuǎn)換后的base64編碼

    var reader = new FileReader();
    var img = $(that).prev("img")
    file = that.files[0]
    reader.addEventListener("load", function () {
     img.attr("src",imgBase64str);
     $("#"+$(that).attr('id')+"base").val(imgBase64str);
    }, false);
    reader.readAsDataURL(file)
   });



  })
  $("#uploadcard").on("click", function(){
   var cardzbase = $("#cardzbase").val();
   if (cardzbase.length<=0) {
    $.toast("請?zhí)砑诱嬲?quot;);
    return;
   }
   $.post(
    "php路徑",
    {
     cardzbase:cardzbase
    },
    function (data) {
     alert(data.msg);
    }
   );


  });
 })
 // 對圖片進(jìn)行壓縮
 function compress(fileObj, callback){
  if ( typeof (FileReader) === 'undefined') {
   console.log("當(dāng)前瀏覽器內(nèi)核不支持base64圖標(biāo)壓縮");
   //調(diào)用上傳方式不壓縮
   directTurnIntoBase64(fileObj,callback);
  } else {
   var reader = new FileReader();
   reader.onload = function (e) { //要先確保圖片完整獲取到,這是個(gè)異步事件


    var image = new Image();
    image.src=e.target.result;
    image.onload = function(){
     square = 0.2,  //定義畫布的大小,也就是圖片壓縮之后的像素
         canvas = document.createElement('canvas'), //創(chuàng)建canvas元素
         context = canvas.getContext('2d'),
         imageWidth = Math.round(square*image.width),  //壓縮圖片的大小
         imageHeight = Math.round(square*image.height),
         data = '';

     canvas.width = imageWidth;
     canvas.height = imageHeight;
     context.clearRect(0, 0, imageWidth, imageHeight); //在給定矩形內(nèi)清空一個(gè)矩形
     context.drawImage(this, 0, 0, imageWidth, imageHeight);
     var data = canvas.toDataURL('image/jpeg',0.6);
     //壓縮完成執(zhí)行回調(diào)

     callback(data);
    };
   };
   reader.readAsDataURL(fileObj);

  }
 }
 // 不對圖片進(jìn)行壓縮,直接轉(zhuǎn)成base64
 function directTurnIntoBase64(fileObj,callback){
  var r = new FileReader();
  // 轉(zhuǎn)成base64
  r.onload = function(){
   //變成字符串
   imgBase64 = r.result;
   //console.log(imgBase64);
   callback(imgBase64);
  }
  r.readAsDataURL(fileObj);  //轉(zhuǎn)成Base64格式
 }
</script>

php

<?php
/**
   * [將Base64圖片轉(zhuǎn)換為本地圖片并保存]
   * @param $base64_image_content [要保存的Base64]
   * @param $path [要保存的路徑]
   * @return bool|string
   */
  public function base64_image_content($base64_image_content,$path){
    //匹配出圖片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
      $type = $result[2];
      //生成文件名
      $file_name = random_str(10).".{$type}";
      //路徑和文件名拼接
      $local_file_url = $path.$file_name;
      if (file_put_contents($local_file_url, base64_decode(str_replace($result[1], '', $base64_image_content)))){
        return array("filename"=>$file_name,"path"=>$path,"filepath"=>$local_file_url);
      }else{
        return false;
      }
    }else{
      return false;
    }
  }

  public function uploadm()
  {
    $da['status'] = 0;
    if (IS_POST) {
      $infoz = I("post.cardzbase");
      if (!$infoz || !$infof) {
        // 上傳錯(cuò)誤提示錯(cuò)誤信息
//        $this->error($upload->getError());
        $da['msg'] = "上傳異常";
      } else {
        $infoz_info = $this->base64_image_content($infoz,"Uploads/verifyinfo/");
        if($infof_info==false){
          $da['msg'] = "上傳失敗";
        }else{
          //自己的業(yè)務(wù)...
        }
      }
    }else{
      $da['msg'] = "非法請求";
    }
    $this->ajaxReturn($da);
  }

感謝各位的閱讀!關(guān)于“怎么通過js實(shí)現(xiàn)壓縮圖片上傳功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

js
AI