【问题标题】:How to set specific compression in Kb using imagejpeg in php如何在 php 中使用 imagejpeg 在 Kb 中设置特定压缩
【发布时间】:2019-07-14 16:31:10
【问题描述】:

我正在尝试将上传的图片压缩到 200Kb 的特定大小。我不想压缩它们超出需要的程度,并且使用像 PNG 这样的无损压缩是不够的。只需将其设置为 imagejpeg($image, null, 40) 即可为不同的图像创建不同的压缩大小。有没有办法以字节为单位设置所需的压缩大小,或者至少有一些算法可以找出压缩输出,而无需循环 imagejpeg() 从 100 到 0 质量?

【问题讨论】:

标签: php image compression jpeg


【解决方案1】:

我找到了一种在上传之前使用ob查看图片文件大小的方法,所以我循环使用了它

// Get get new image data
    ob_start();
    // Build image with minimal campression
    imagejpeg($newImage, NULL, 100);
    // Get the size of the image file in bytes
    $size = ob_get_length();
    // Save new image into a variable
    $compressedImage = addslashes(ob_get_contents());
    // Clear memory
    ob_end_clean();

    // If image is larger than 200Kb
    if ($size > 200000) {
      // This variable will decrease by 2 every loop to try most combinations 
      // from least compressed to most compressed
      $compressionValue = 100;
      for ($i=0; $i < 50; $i++) {
        $compressionValue = $compressionValue - 2;
        ob_start();
        imagejpeg($newImage, NULL, $compressionValue);
        $size = ob_get_length();
        // Overwrite old compressed image with the new compressed image
        $compressedImage = addslashes(ob_get_contents());
        // Clear memory
        ob_end_clean();
        // If image is less than or equal to 200.5Kb stop the loop
        if ($size <= 200500) {
          break;
        }
      }
    }

这本身也得到了难以置信的优化。一个 1.5Mb 的起始图像,即使尝试 50 种组合,整个过程也只需要几毫秒。

【讨论】:

    【解决方案2】:

    确实没有任何方法可以预先预测压缩级别。压缩效果取决于图像源。问题之一是存在无数的 JPEG 压缩设置。

    1. 具有 64 个不同值的量化表(最多 3 个)。
    2. 子抽样。
    3. 逐行扫描中的光谱选择。
    4. 逐行扫描中的逐次逼近。
    5. 优化霍夫曼表。

    因此,您可以设置数十亿个参数。

    有一些 JPEG 优化应用程序可以查看压缩数据。

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 2012-01-17
      • 1970-01-01
      • 2010-11-22
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多