hugo/content/en/content-management/image-processing/index.md
Bjørn Erik Pedersen 07b8d9466d Squashed 'docs/' changes from 9cece6640..fb551cc75
fb551cc75 Update index.md
7af894857 Update index.md
d235753ea Hugo 0.82.1
e03e72deb Merge branch 'temp0821'
e62648961 Merge branch 'release-0.82.1'
e1ab0f6eb releaser: Add release notes to /docs for release of 0.82.1
5d354c38d Replaced ``` code blocks with Code Toggler
c9d065c20 Remove duplicate YAML keys (#1420)
8ae31e701 Add webp image encoding support
848f2af26 Update internal.md (#1407)
c103a86a4 Fix `ref` shortcode example output (#1409)
9f8ba56dc Remove leading dot from where function KEY (#1419)
363251a51 Improve presentation of template lookup order (#1382)
b73da986d Improve description of Page Resources (#1381)
4e0bb96d5 Rework robots.txt page (#1405)
edf893e6f Update migrations.md (#1412)
450f1580b Add link to `site` function doc (#1417)
cfffa6e6f Added one extension to the list (#1414)
05f1665a0 Update theme
5de0b1c6a Update theme
250e20552 Add hugo.IsExtended
dea5e1fd7 Fix typo on merge function page (#1408)
1bbed2cf3 Update configuration.md
be0b64a46 Omit ISO
cbb5b8367 Fix `dateFormat` documentation
698f15466 Regenerate the docshelper
f9a8a7cb6 Update multilingual.md
a22dc6267 Fix grammar (#1398)
eb98b0997 Fix pretty URL example (#1397)
f4c4153dc Mention date var complementation in post scheduling (#1396)
17fae284c Fix resources.ExecuteAsTemplate argument order (#1394)
97e2c2abb Use code-toggle shortcode in `multilingual.md` (#1388)
3a84929bb Harmonize capitalization (#1393)
17f15daa6 fix file naming used in example (#1392)
5d97b6a18 Add slice syntax to sections permalinks config
00665b97b Improve description of `site.md`
edcf5e3fc Fix example in `merge.md`
f275ab778 Update postprocess.md
9593e3991 Fix file name
59bd9656f Update postprocess.md
1172fb6d0 Update to theNewDynamic repository (#1263)
f5b5c1d2c Update Hugo container image
4f2e92f2a Adapt anchorize.md to Goldmark
98aa19073 Directly link to `highlight` shortcode (#1384)
4c75c2422 Fix header level
f15c06f23 markdownify: add note about render-hooks and .RenderString (#1281)
69c82eb68 Remove Blackfriday reference from shortcode desc (#1380)
36de478df Update description of ignoreFiles config setting (#1377)
6337699d8 Remove "Authors" page from documentation (#1371)
35e73ca90 fix indent in example (#1372)
d3f01f19a Remove opening body tag from header example (#1376)
341a5a7d8 Update index.md
c9bfdbee6 Release 0.82.0
119644949 releaser: Add release notes to /docs for release of 0.82.0
32efaed78 docs: Regenerate docs helper
dea5449a2 docs: Regen CLI docs
eeab18fce Merge commit '81689af79901f0cdaff765cda6322dd4a9a7ccb3'
d508a1259 Attributes for code fences should be placed after the lang indicator only
c80905cef deps: Update to esbuild v0.9.0
95350eb79 Add support for Google Analytics v4
02d36f9bc Allow markdown attribute lists to be used in title render hooks
7df220a64 Merge commit '9d31f650da964a52f05fc27b7fb99cf3e09778cf'
d80bf61b7 Fixes #7698.

git-subtree-dir: docs
git-subtree-split: fb551cc750faa83a1493b0e0d0898cd98ab74465
2021-04-20 20:21:45 +02:00

11 KiB

title description date linktitle categories keywords weight draft toc menu
Image Processing Image Page resources can be resized and cropped. 2018-01-24T13:10:00-05:00 Image Processing
content management
resources
images
4004 false true
docs
parent weight
content-management 32

The Image Page Resource

The image is a [Page Resource]({{< relref "/content-management/page-resources" >}}), and the processing methods listed below do not work on images inside your /static folder.

To print all images paths in a [Page Bundle]({{< relref "/content-management/organization#page-bundles" >}}):

{{ with .Resources.ByType "image" }}
{{ range . }}
{{ .RelPermalink }}
{{ end }}
{{ end }}

The Image Resource

The image resource can also be retrieved from a [global resource]({{< relref "/hugo-pipes/introduction#from-file-to-resource" >}})

{{- $image := resources.Get "images/logo.jpg" -}}

Image Processing Methods

The image resource implements the Resize, Fit, Fill, and Filter methods, each returning a transformed image using the specified dimensions and processing options.

{{% note %}} Metadata (EXIF, IPTC, XMP, etc.) is not preserved during image transformation. Use the Exif method with the original image to extract EXIF metadata from JPEG or TIFF images. {{% /note %}}

Resize

Resizes the image to the specified width and height.

// Resize to a width of 600px and preserve ratio
{{ $image := $resource.Resize "600x" }}

// Resize to a height of 400px and preserve ratio
{{ $image := $resource.Resize "x400" }}

// Resize to a width 600px and a height of 400px
{{ $image := $resource.Resize "600x400" }}

Fit

Scale down the image to fit the given dimensions while maintaining aspect ratio. Both height and width are required.

{{ $image := $resource.Fit "600x400" }}

Fill

Resize and crop the image to match the given dimensions. Both height and width are required.

{{ $image := $resource.Fill "600x400" }}

Filter

Apply one or more filters to your image. See Image Filters for a full list.

{{ $img = $img.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}

The above can also be written in a more functional style using pipes:

{{ $img = $img | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}

The filters will be applied in the given order.

Sometimes it can be useful to create the filter chain once and then reuse it:

{{ $filters := slice  (images.GaussianBlur 6) (images.Pixelate 8) }}
{{ $img1 = $img1.Filter $filters }}
{{ $img2 = $img2.Filter $filters }}

Exif

Provides an Exif object with metadata about the image.

Note that this is only supported for JPEG and TIFF images, so it's recommended to wrap the access with a with, e.g.:

{{ with $img.Exif }}
Date: {{ .Date }}
Lat/Long: {{ .Lat}}/{{ .Long }}
Tags:
{{ range $k, $v := .Tags }}
TAG: {{ $k }}: {{ $v }}
{{ end }}
{{ end }}

Or individually access EXIF data with dot access, e.g.:

{{ with $src.Exif }}
  <ul>
      {{ with .Date }}<li>Date: {{ .Format "January 02, 2006" }}</li>{{ end }}
      {{ with .Tags.ApertureValue }}<li>Aperture: {{ lang.NumFmt 2 . }}</li>{{ end }}
      {{ with .Tags.BrightnessValue }}<li>Brightness: {{ lang.NumFmt 2 . }}</li>{{ end }}
      {{ with .Tags.ExposureTime }}<li>Exposure Time: {{ . }}</li>{{ end }}
      {{ with .Tags.FNumber }}<li>F Number: {{ . }}</li>{{ end }}
      {{ with .Tags.FocalLength }}<li>Focal Length: {{ . }}</li>{{ end }}
      {{ with .Tags.ISOSpeedRatings }}<li>ISO Speed Ratings: {{ . }}</li>{{ end }}
      {{ with .Tags.LensModel }}<li>Lens Model: {{ . }}</li>{{ end }}
  </ul>
{{ end }}

Some fields may need to be formatted with [lang.NumFmt]({{< relref "functions/numfmt" >}}) function to prevent display like Aperture: 2.278934289 instead of Aperture: 2.28.

Exif fields

Date
"photo taken" date/time
Lat
"photo taken where", GPS latitude
Long
"photo taken where", GPS longitude

See Image Processing Config for how to configure what gets included in Exif.

Image Processing Options

In addition to the dimensions (e.g. 600x400), Hugo supports a set of additional image options.

Background Color

The background color to fill into the transparency layer. This is mostly useful when converting to a format that does not support transparency, e.g. JPEG.

You can set the background color to use with a 3 or 6 digit hex code starting with #.

{{ $image.Resize "600x jpg #b31280" }}

For color codes, see https://www.google.com/search?q=color+picker

Note that you also set a default background color to use, see Image Processing Config.

JPEG and Webp Quality

Only relevant for JPEG and Webp images, values 1 to 100 inclusive, higher is better. Default is 75.

{{ $image.Resize "600x q50" }}

{{< new-in "0.83.0" >}} Webp support was added in Hugo 0.83.0.

Hint {{< new-in "0.83.0" >}}

Hint about what type of image this is. Currently only used when encoding to Webp.

Default value is photo.

Valid values are picture, photo, drawing, icon, or text.

{{ $image.Resize "600x webp drawing" }}

Rotate

Rotates an image by the given angle counter-clockwise. The rotation will be performed first to get the dimensions correct. The main use of this is to be able to manually correct for EXIF orientation of JPEG images.

{{ $image.Resize "600x r90" }}

Anchor

Only relevant for the Fill method. This is useful for thumbnail generation where the main motive is located in, say, the left corner.

Valid values are Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight.

Default value is Smart, which uses Smartcrop to determine the best crop.

{{ $image.Fill "300x200 BottomLeft" }}

Resample Filter

Filter used in resizing. Default is Box, a simple and fast resampling filter appropriate for downscaling.

Examples are: Box, NearestNeighbor, Linear, Gaussian.

See https://github.com/disintegration/imaging for more. If you want to trade quality for faster processing, this may be a option to test.

{{ $image.Resize "600x400 Gaussian" }}

Target Format

By default the images is encoded in the source format, but you can set the target format as an option.

Valid values are jpg, png, tif, bmp, and gif.

{{ $image.Resize "600x jpg" }}

Image Processing Examples

The photo of the sunset used in the examples below is Copyright Bjørn Erik Pedersen (Creative Commons Attribution-Share Alike 4.0 International license)

{{< imgproc sunset Resize "300x" />}}

{{< imgproc sunset Fill "90x120 left" />}}

{{< imgproc sunset Fill "90x120 right" />}}

{{< imgproc sunset Fit "90x90" />}}

{{< imgproc sunset Resize "300x q10" />}}

This is the shortcode used in the examples above:

{{< code file="layouts/shortcodes/imgproc.html" >}} {{< readfile file="layouts/shortcodes/imgproc.html" >}}
{{< /code >}}

And it is used like this:

{{</* imgproc sunset Resize "300x" /*/>}}

{{% note %}} Tip: Note the self-closing shortcode syntax above. The imgproc shortcode can be called both with and without inner content. {{% /note %}}

Image Processing Config

You can configure an imaging section in config.toml with default image processing options:

[imaging]
# Default resample filter used for resizing. Default is Box,
# a simple and fast averaging filter appropriate for downscaling.
# See https://github.com/disintegration/imaging
resampleFilter = "box"

# Default JPEG or WEBP quality setting. Default is 75.
quality = 75

# Default hint about what type of image. Currently only used for Webp encoding.
# Default is "photo".
# Valid values are "picture", "photo", "drawing", "icon", or "text".
hint = "photo"

# Anchor used when cropping pictures.
# Default is "smart" which does Smart Cropping, using https://github.com/muesli/smartcrop
# Smart Cropping is content aware and tries to find the best crop for each image.
# Valid values are Smart, Center, TopLeft, Top, TopRight, Left, Right, BottomLeft, Bottom, BottomRight
anchor = "smart"

# Default background color.
# Hugo will preserve transparency for target formats that supports it,
# but will fall back to this color for JPEG.
# Expects a standard HEX color string with 3 or 6 digits.
# See https://www.google.com/search?q=color+picker
bgColor = "#ffffff"

[imaging.exif]
 # Regexp matching the fields you want to Exclude from the (massive) set of Exif info
# available. As we cache this info to disk, this is for performance and
# disk space reasons more than anything.
# If you want it all, put ".*" in this config setting.
# Note that if neither this or ExcludeFields is set, Hugo will return a small
# default set.
includeFields = ""

# Regexp matching the Exif fields you want to exclude. This may be easier to use
# than IncludeFields above, depending on what you want.
excludeFields = ""

# Hugo extracts the "photo taken" date/time into .Date by default.
# Set this to true to turn it off.
disableDate = false

# Hugo extracts the "photo taken where" (GPS latitude and longitude) into
# .Long and .Lat. Set this to true to turn it off.
disableLatLong = false


Smart Cropping of Images

By default, Hugo will use Smartcrop, a library created by muesli, when cropping images with .Fill. You can set the anchor point manually, but in most cases the smart option will make a good choice. And we will work with the library author to improve this in the future.

An example using the sunset image from above:

{{< imgproc sunset Fill "200x200 smart" />}}

Image Processing Performance Consideration

Processed images are stored below <project-dir>/resources (can be set with resourceDir config setting). This folder is deliberately placed in the project, as it is recommended to check these into source control as part of the project. These images are not "Hugo fast" to generate, but once generated they can be reused.

If you change your image settings (e.g. size), remove or rename images etc., you will end up with unused images taking up space and cluttering your project.

To clean up, run:

hugo --gc

{{% note %}} GC is short for Garbage Collection. {{% /note %}}