zoukankan      html  css  js  c++  java
  • 图片压缩

    • 将图片压缩成jpg或png
      $type = explode('/', $file->type);
      $mainType = $type[0];
      $subType = $type[1];
      $isImage = $mainType == 'image';
      $isGif = $subType == 'gif';//gif压缩会变静态的,所以过滤掉
      if ($isImage) {
          $maxSize = 1024 * 1024;
          if (!$isGif) {
              //图片进行压缩
              $file->data = $this->compressImage($file->data, $maxSize);
          }
          //生成文件
      }
      
      function compressImage($data, $maxSize, $percent = 1) {
          $size = strlen($data);
          if ($size <= $maxSize) {
              return $data;
          }
      
          $img = imagecreatefromstring($data);
          $width = imagesx($img);
          $height = imagesy($img);
      
          $newWidth = $width * $percent;
          $newHeight = $height * $percent;
      
          $newImg = imagecreatetruecolor($newWidth, $newHeight);
          imagecopyresampled($newImg, $img, 0, 0, 0, 0, floor($newWidth), floor($newHeight), $width, $height);
      
          ob_start(); //Turn on output buffering
          imagepng($newImg); //Generate your image
          //imagejpeg($newImg); 
          $data = $output = ob_get_contents(); // get the image as a string in a variable
          ob_end_clean(); //Turn off output buffering and clean it
          imagedestroy($newImg);
          $percent -= 0.1;
          print_r("
      percent={$percent},size={$size}");
          return self::compressImage($data, $maxSize,$percent);
      }
    • jpg
      • 4.58M:(1)710KB[4]
      • 3.78M:(2)267KB[1]
      • 1.38M:(3)718KB[1]
    • png
      • 4.58M:(1)997.29[6]
      • 3.78M:(2)982.2KB[4]
      • 1.38M:(3)928KB[5]
  • 相关阅读:
    BZOJ 1021 循环的债务
    BZOJ 1019 汉诺塔
    BZOJ 1018 堵塞的交通
    BZOJ 1017 魔兽地图
    BZOJ 1016 最小生成树计数
    Luogu 3008 [USACO11JAN]道路和飞机Roads and Planes
    Luogu 3625 [APIO2009]采油区域
    Luogu 4139 上帝与集合的正确用法
    Luogu 3629 [APIO2010]巡逻
    Luogu 3626 [APIO2009]会议中心
  • 原文地址:https://www.cnblogs.com/fatRabbit-/p/11393442.html
Copyright © 2011-2022 走看看