首页 > 解决方案 > 如何在 php 中使用 imagejpeg 在 Kb 中设置特定压缩

问题描述

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

标签: phpimagecompressionjpeg

解决方案


我找到了一种在上传之前使用 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;
        }
      }
    }

这本身也得到了非常好的优化。即使尝试 50 种组合,对于 1.5Mb 的起始图像,整个过程也只需要几毫秒。


推荐阅读