Skip to content
Permalink
Browse files

Minor fixes in max_bytes docs & code

  • Loading branch information...
DarthSim committed Nov 29, 2019
1 parent d74c402 commit 25a6c9ba3963862fd17724765392489f3de38de0
Showing with 33 additions and 31 deletions.
  1. +1 −0 CHANGELOG.md
  2. +5 −4 docs/generating_the_url_advanced.md
  3. +27 −27 process.go
@@ -3,6 +3,7 @@
## [Unreleased]
### Added
- `IMGPROXY_LOG_LEVEL` config.
- `max_bytes` processing option.

### Changed
- Docker image base is changed to Debian 10 for better stability and performance.
@@ -172,13 +172,14 @@ Default: value from the environment variable.
#### Max Bytes

```
max_bytes:%max_bytes
mb:%max_bytes
max_bytes:%bytes
mb:%bytes
```

This filter automatically degrades the quality of the image until the image is under the specified amount of bytes.
When set, imgproxy automatically degrades the quality of the image until the image is under the specified amount of bytes.

*Warning: this filter processes image multiple times to achieve specified image size*
**Note:** Applicable only to `jpg`, `webp`, `heic`, and `tiff`.
**Warning**: When `max_bytes` is set, imgproxy saves image multiple times to achieve specified image size.

Default: 0

@@ -586,6 +586,32 @@ func getIcoData(imgdata *imageData) (*imageData, error) {
return nil, fmt.Errorf("Can't load %s from ICO", meta.Format)
}

func saveImageToFitBytes(po *processingOptions, img *vipsImage) ([]byte, context.CancelFunc, error) {
var diff float64
quality := po.Quality

img.CopyMemory()

for {
result, cancel, err := img.Save(po.Format, quality)
if len(result) <= po.MaxBytes || quality <= 10 || err != nil {
return result, cancel, err
}
cancel()

delta := float64(len(result)) / float64(po.MaxBytes)
switch {
case delta > 3:
diff = 0.25
case delta > 1.5:
diff = 0.5
default:
diff = 0.75
}
quality = int(float64(quality) * diff)
}
}

func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
@@ -692,34 +718,8 @@ func processImage(ctx context.Context) ([]byte, context.CancelFunc, error) {
}

if po.MaxBytes > 0 && canFitToBytes(po.Format) {
return processToFitBytes(po, img)
return saveImageToFitBytes(po, img)
}

return img.Save(po.Format, po.Quality)
}

func processToFitBytes(po *processingOptions, img *vipsImage) ([]byte, context.CancelFunc, error) {
var diff float64
quality := po.Quality

img.CopyMemory()

for {
result, cancel, err := img.Save(po.Format, quality)
if len(result) <= po.MaxBytes || quality <= 10 || err != nil {
return result, cancel, err
}
cancel()

delta := float64(len(result)) / float64(po.MaxBytes)
switch {
case delta > 3:
diff = 0.25
case delta > 1.5:
diff = 0.5
default:
diff = 0.75
}
quality = int(float64(quality) * diff)
}
}

0 comments on commit 25a6c9b

Please sign in to comment.
You can’t perform that action at this time.