Skip to content

Commit 12247bc

Browse files
authored
fix ImageManager::compressUntilSize() (#2200)
1 parent 0a0d732 commit 12247bc

2 files changed

Lines changed: 7 additions & 5 deletions

File tree

docs/02-admin/03-optional-features/09-image-compression.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
You can enable compression of images uploaded to mbin by users or downloaded from remote instances,
44
for increased compatibility, to save on size and for a better user experience.
55

6-
To enable image compression set `MBIN_IMAGE_COMPRESSION_QUALITY` in your `.env` file to a value between 0.1 and 0.95.
6+
To enable image compression set `MBIN_IMAGE_COMPRESSION_QUALITY` in your `.env` file to a value between 0.3 and 0.95.
77
This setting is used as a starting point to compress the image. It is gradually lowered (in 0.05 steps) until the maximum size is no longer exceeded.
88

99
> [!TIP]

src/Service/ImageManager.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,33 +95,35 @@ public function store(string $source, string $filePath): bool
9595
*/
9696
public function compressUntilSize(string $filePath, string $extension, int $maxBytes): bool
9797
{
98-
if (-1 === $this->imageCompressionQuality || filesize($filePath) <= $maxBytes) {
98+
if (-1 === (int) $this->imageCompressionQuality || filesize($filePath) <= $maxBytes) {
9999
// don't compress images if disabled or smaller than max bytes
100100
return false;
101101
}
102102
$imagine = new Imagine();
103103
$image = $imagine->open($filePath);
104104
$bytes = filesize($filePath);
105105
$initialBytes = $bytes;
106+
$lastBytes = $bytes;
106107
$tempPath = "{$filePath}_temp_compress.$extension";
107108
$compressed = false;
108109
$quality = 0.9;
109-
if (0.1 <= $this->imageCompressionQuality && 1 > $this->imageCompressionQuality) {
110+
if (0.3 <= $this->imageCompressionQuality && 1 > $this->imageCompressionQuality) {
110111
$quality = $this->imageCompressionQuality;
111112
}
112-
while ($bytes > $maxBytes && $quality > 0.1) {
113+
while ($bytes > $maxBytes && $quality > 0.3) {
113114
$this->logger->debug('[ImageManager::compressUntilSize] Trying to compress "{path}" with {q}% quality', ['path' => $tempPath, 'q' => $quality * 100]);
114115
$image->save($tempPath, [
115116
'jpeg_quality' => $quality * 100, // jpeg max value is 100
116117
'png_compression_level' => 9, // this is lossless compression, so always use the max
117118
'webp_quality' => $quality * 100, // webp quality max is 100
118119
]);
119120
$bytes = filesize($tempPath);
120-
if ($initialBytes === $bytes) {
121+
if ($lastBytes === $bytes) {
121122
// there were no changes, so maybe it is in a format that cannot be compressed...
122123
break;
123124
}
124125
$compressed = true;
126+
$lastBytes = $bytes;
125127
$quality -= 0.05;
126128
}
127129
$copied = false;

0 commit comments

Comments
 (0)