Browse Source

Minor fixes in max_bytes docs & code

DarthSim 5 năm trước cách đây
mục cha
commit
25a6c9ba39
3 tập tin đã thay đổi với 33 bổ sung31 xóa
  1. 1 0
      CHANGELOG.md
  2. 5 4
      docs/generating_the_url_advanced.md
  3. 27 27
      process.go

+ 1 - 0
CHANGELOG.md

@@ -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.

+ 5 - 4
docs/generating_the_url_advanced.md

@@ -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
 

+ 27 - 27
process.go

@@ -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)
-	}
-}