Missing pixels on resize/crop

I have weird cases of missing pixels on all processed images:

{{- $image := .Resize "1200x" -}}
{{- $cropOptions := printf "1200x627 %s" $default_format -}}
{{- $image = $image.Crop $cropOptions -}}
{{- $metaProperty = (dict
      "property" "og:image"
      "content" $image.Permalink) -}}

The code above ($default_format is tested with ‘webp’ and ‘jpg’) where all resulting images turn out to be 1199x626 instead of 1200x627. The original images are all larger than 3000 pixels wide and the aspect ratio is not 1200x627 (1.91:1).

Changing default format between webp/jpg and changing the sizes still result in the values minus 1 pixel wide and high images.

Is there any way to crop them properly, or do I have to “fake” it by adding pixels on all sizes? Or is there anything wrong with the order/methods I am using?

Not sure if this will help - Hugo uses the GIFT module to resize and Smartcrop to crop images using a heuristic color “hot map” to find the best crop consistent with the supplied dimensions. It is possible that integer math might be a possible reason for the off-by-one that you see. Some time ago, I wanted to test the output of these libraries and compare them with what Hugo generates. You can find my code here. It might help to add some debug statements to see what each stage (resize → crop) generates using the same libraries that Hugo uses.

Also do consider using Fit if you would like to test the output in one go rather than Resize and then Crop

1 Like

I actually tried the .Fit method too, but it also cut off too much… which brought me to the .Fill method which works as expected :wink: .Fit seems to resize but keeping the aspect ratio, .Fill resizes and crops what hangs over on one of the sides.

Also, using only .Crop results in proper measurements. I think Hugo (or the Module(s) used) has a little problem with rounding too cautiously down.

My specific use case is solved with the .Fill method. Sooooo… solved :smiley:

1 Like

Is the value of .Width 1199?

Yes

{{- $image := .Resize "1200x" -}}
{{- $cropOptions := printf "1200x630 %s" $default_format -}}
{{- $image = $image.Crop $cropOptions -}}
...
{{- $image.Width }} /// {{- $image.Height }}

results in

1199 /// 629

Hmm. OK. I asked because we have many testcases where assertion of width/height is part of the test, and I have never seen this “off by one” before.

I checked all the images on the documentation page, and there is nothing 1 pixel off. I have the feeling that the “resizing plus cropping chain” is doing something, because just cropping resulted in proper dimensions. It’s weird, but .Fill works fine and takes a step out of the processing list.

You can get some more data points looking at https://themes.gohugo.io/

Create a GitHub issue with a link back to this discussion. This looks like a bug … somehwere that needs to be fixed.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.