hugo/content/en/content-management/image-processing/index.md
Bjørn Erik Pedersen f96384a3b5 Squashed 'docs/' changes from 6e32d0591..39af43ef1
39af43ef1 Update postprocess.md
3ec192d08 Update multilingual.md
7fc7bf862 Add a note about some changes in 0.112.0
742510ae8 Fix ordinal abbrev example
fe557031a Correct spelling for 'GitHub' and 'GitLab' (#2082)
84a059b9a Fix typo in hosting-on-azure.md (#2080)
3383786fe Add i18n to list of directories affected by ignoreFiles
5bfb95234 Update 404.md (#2076)
87545a4fd Update hosting-on-cloudflare-pages.md (#2078)
aa5952c28 Add default module mount to example (#2075)
ced5292c8 Align permalinks examples (#2073)
77b5009fd Fix typo
c79319a6a Clarify description of baseURL
e93a9807b Fix typo in frontmatter description (#2071)
05fe9163a Remove erroneous statement
aa59ef383 docs: Remove note about hugo server not using 404 (#2068)
4a387a6b8 Clarify findRESubmatch (#2065)
47a9181b5 Clarify findRE, replaceRE, and findRESubmatch (#2064)
e5eedbb5e Update theme
5d392c3d4 Clarify pageRef menu property (#2059)
a557b0ebf Fix typos on Configure Hugo page (#2058)
17ef283e6 Clarify module.replacements wording (#2052)
5db4aa421 Fixing broken links (#2057)
9afa0c2fa Fix broken links (#2055)
49b981b1f Correct repo URL for migration tool (contentful.com) (#2056)
969c24c16 Remove duplicate content
0b91e7676 Revert "Delete duplicate content"
3229e79f2 Delete duplicate content
ec4eddb98 Fix typo
6509159d5 Describe snap package strict confinement (#2050)
1589bcdb7 Remove hugo.Generator admonition (#2048)
7e553d11b Add example
48bec0335 Replace blockquotes with admonitions where appropriate (#2043)
98226fe61 Remove orphaned param fron admonition calls (#2042)
2a37a1d21 Clarify cast functions (#2041)
03fd1d404 Fix typo
1898013ef Fix typos
944e27430 Replace output shortcode calls
0c66fb055 Add example of shortcode calls within sample code
f25a79c69 Replace tip and warning shortcode calls
3afac22fc Refactor code shortcode
ad65d2931 Clarify seq function
59f8a1f48 Clarify title function
47535dc87 Cleanup hasPrefix hasSuffix
7bee3e4c1 Cleanup action delimiters
cc96070f0 Correct functions archetype
ffe5d39b9 Remove duplicate shortcodes
075c9f3fe Remove old todos
bc3ec033c Front matter cleanup (#2039)
928b94505 Add code fence types (#2038)
856fa293c Document .File.Filename (#2037)
0988c4a42 Update output-formats.md (#2036)
289da5658 Change findRe to findRE
1e50f0583 Update theme
f90fb1bf5 Improve type formatting (#2032)
7785fa7d9 Use code-toggle shortcode where appropriate
f11cabf37 Add space after and before action delimiters
ac333c795 Replace erroneous use of nocopy shortcode param
064896c06 Use bool param when calling code-toggle
fb33bf59b Update code-toggle shortcode
6ddeab4f8 Add missing go-html-template code fence type (#2030)
1bba4cefb Fix links (#2029)
77f4d6c32 Link destination cleanup (#2028)
fc0ecc027 Improve breadcrumb example (#2026)
6148be2de Update the breadcrumb navigation example (#2025)
6ebb37b1b Clarify sort function (#2024)
31269bad9 Add Winget installation method (#1988)
d6c5f940e Resource methods: add signatures, minor improvements (#2017)
d2e594cbc Modify inner variable shortcode-template explanation (#1985)
a54927a7f Update GitHub Pages starter workflow (#2023)
2964c2d44 Remove orphaned static files (#2022)
97e5567cc Complete documentation on '.Scratch' and '.Store' (#2016)
fa7b2e299 Fix typo
bdce77c57 Remove literal from example menu template
c0f23b216 Correct and improve menu documentation (#2010)
464368fd9 Document .Page.Store (#2011)
a3d7c4a3a Improve urls.Parse function (#2012)
d2cec3776 Clarify postcss config option (#2013)
eb3003fef Fixed typo (#2007)
90c82d7ea Clarify mermaid markdown example (#2004)
1b11dcd5c docs(Diagrams): Update mermaid import mechanism (#1967)
4aceb6855 Fingerprinting, asset management: minor improvements (#2003)
bcbc519bb resources.GetRemote: minor improvement (#2002)
d54185bef Clarify markdownify behavior (#1999)
afb582a80 Clarify usage of slug in front matter (#1998)
f71985315 Update hasSuffix.md
29ad622a3 netlify: Hugo 0.111.3
adf223ecc Merge branch 'tempv0.111.3'
06858c646 docs: Improve examples of variadic math functions
8b656994e tpl/math: Allow multi numbers in add, sub, mul, div, min and max
2a38c4046 tpl: Add hasSuffix alias
4e0b98d54 switch transfers to workers
11651ac0f customize parallel transfer count
142f5da81 Update GitHub hosting instructions (#1991)
ad7901d2f netlify: Hugo 0.111.2
0651a76e0 add headings to distinguish render hook context params
d96d75be4 netlify: Hugo 0.111.1
226cb9e3a Add a paragraph about the new page template function
4c0157a49 Add .Fragments docs
6c78c0679 netlify: Bump to Hugo 0.111.0
7b11c24cf Merge branch 'feat/related-fragments'
615d18ef8 Add Related fragments config
a36449b0c cods: Regen docs helper
0272fa45f Merge commit '336622d5e7afd9334cd2de7150d4f16bdf7c24f9'
c5a962b93 related: Add config option cardinalityThreshold
f91677377  docs: Another fix related docs example
17aa939ea docs: Fix related docs example
12c449150 Merge commit 'cf591b7c0c598d34896709db6d28598da37e3ff6'
cb998b3d6 Add page fragments support to Related

git-subtree-dir: docs
git-subtree-split: 39af43ef11c23b8eaea7e17b59ff065a169305ac
2023-05-22 16:43:12 +02:00

16 KiB

title description categories keywords menu toc weight
Image Processing Resize, crop, rotate, filter, and convert images.
content management
resources
images
docs
parent weight
content-management 90
true 90

Image Resources

To process an image, you must access the image as either a page resource or a global resource.

Page Resources

A page resource is a file within a page bundle. A page bundle is a directory with an index.md or _index.md file at its root.

content/
└── posts/
    └── post-1/           <-- page bundle
        ├── index.md
        └── sunset.jpg    <-- page resource

Global Resources

A global resource is a file:

  • Within the assets directory, or
  • Within any directory mounted to the assets directory, or
  • Located on a remote server accessible via http or https
assets/
└── images/
    └── sunset.jpg    <-- global resource

To access a local image as a global resource:

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

To access a remote image as a global resource:

{{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }}

Image Rendering

Once you have accessed an image as either a page resource or a global resource, render it in your templates using the Permalink, RelPermalink, Width, and Height properties.

Example 1: Throws an error if the resource is not found.

{{ $image := .Resources.GetMatch "sunset.jpg" }}
<img src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}">

Example 2: Skips image rendering if the resource is not found.

{{ $image := .Resources.GetMatch "sunset.jpg" }}
{{ with $image }}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
{{ end }}

Example 3: A more concise way to skip image rendering if the resource is not found.

{{ with .Resources.GetMatch "sunset.jpg" }}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
{{ end }}

Image Processing Methods

The image resource implements the Resize, Fit, Fill, Crop, Filter, Colors and Exif methods.

{{% 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

Resize an image to the specified width and/or height.

If you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio.

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

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

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

Fit

Downscale an image to fit the given dimensions while maintaining aspect ratio. You must provide both width and height.

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

Fill

Crop and resize an image to match the given dimensions. You must provide both width and height. Use the anchor option to change the crop box anchor point.

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

Crop

Crop an image to match the given dimensions without resizing. You must provide both width and height. Use the anchor option to change the crop box anchor point.

{{ $image := $image.Crop "600x400" }}

Filter

Apply one or more filters to an image.

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

Write this in a more functional style using pipes. Hugo applies the filters in the order given.

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

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

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

Colors

{{< new-in "0.104.0" >}}

.Colors returns a slice of hex strings with the dominant colors in the image using a simple histogram method.

{{ $colors := $image.Colors }}

This method is fast, but if you also scale down your images, it would be good for performance to extract the colors from the scaled down image.

Exif

Provides an Exif object containing image metadata.

You may access Exif data in JPEG and TIFF images. To prevent errors when processing images without Exif data, wrap the access in a with statement.

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

You may also access Exif fields individually, using the lang.FormatNumber function to format the fields as needed.

{{ with $image.Exif }}
  <ul>
    {{ with .Date }}<li>Date: {{ .Format "January 02, 2006" }}</li>{{ end }}
    {{ with .Tags.ApertureValue }}<li>Aperture: {{ lang.FormatNumber 2 . }}</li>{{ end }}
    {{ with .Tags.BrightnessValue }}<li>Brightness: {{ lang.FormatNumber 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 }}

Exif Variables

.Date
Image creation date/time. Format with the time.Format function.
.Lat
GPS latitude in degrees.
.Long
GPS longitude in degrees.
.Tags
A collection of the available Exif tags for this image. You may include or exclude specific tags from this collection in the site configuration.

Image Processing Options

The Resize, Fit, Fill, and Crop methods accept a space-separated, case-insensitive list of options. The order of the options within the list is irrelevant.

Dimensions

With the Resize method you must specify width, height, or both. The Fit, Fill, and Crop methods require both width and height. All dimensions are in pixels.

{{ $image := $image.Resize "600x" }}
{{ $image := $image.Resize "x400" }}
{{ $image := $image.Resize "600x400" }}
{{ $image := $image.Fit "600x400" }}
{{ $image := $image.Fill "600x400" }}
{{ $image := $image.Crop "600x400" }}

Rotation

Rotates an image counter-clockwise by the given angle. Hugo performs rotation before scaling. For example, if the original image is 600x400 and you wish to rotate the image 90 degrees counter-clockwise while scaling it by 50%:

{{ $image = $image.Resize "200x r90" }}

In the example above, the width represents the desired width after rotation.

To rotate an image without scaling, use the dimensions of the original image:

{{ with .Resources.GetMatch "sunset.jpg" }}
  {{ with .Resize (printf "%dx%d r90" .Height .Width) }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
  {{ end }}
{{ end }}

In the example above, on the second line, we have reversed width and height to reflect the desired dimensions after rotation.

Anchor

When using the Crop or Fill method, the anchor determines the placement of the crop box. You may specify TopLeft, Top, TopRight, Left, Center,Right, BottomLeft, Bottom, BottomRight, or Smart.

The default value is Smart, which uses Smartcrop image analysis to determine the optimal placement of the crop box. You may override the default value in the site configuration.

For example, if you have a 400x200 image with a bird in the upper left quadrant, you can create a 200x100 thumbnail containing the bird:

{{ $image.Crop "200x100 TopLeft" }}

If you apply rotation when using the Crop or Fill method, specify the anchor relative to the rotated image.

Target Format

By default, Hugo encodes the image in the source format. You may convert the image to another format by specifying bmp, gif, jpeg, jpg, png, tif, tiff, or webp.

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

To convert an image without scaling, use the dimensions of the original image:

{{ with .Resources.GetMatch "sunset.jpg" }}
  {{ with .Resize (printf "%dx%d webp" .Width .Height) }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
  {{ end }}
{{ end }}

Quality

Applicable to JPEG and WebP images, the q value determines the quality of the converted image. Higher values produce better quality images, while lower values produce smaller files. Set this value to a whole number between 1 and 100, inclusive.

The default value is 75. You may override the default value in the site configuration.

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

Hint

Applicable to WebP images, this option corresponds to a set of predefined encoding parameters.

Value Example
drawing Hand or line drawing with high-contrast details
icon Small colorful image
photo Outdoor photograph with natural lighting
picture Indoor photograph such as a portrait
text Image that is primarily text

The default value is photo. You may override the default value in the site configuration.

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

Background Color

When converting an image from a format that supports transparency (e.g., PNG) to a format that does not support transparency (e.g., JPEG), you may specify the background color of the resulting image.

Use either a 3-digit or a 6-digit hexadecimal color code (e.g., #00f or #0000ff).

The default value is #ffffff (white). You may override the default value in the site configuration.

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

Resampling Filter

You may specify the resampling filter used when resizing an image. Commonly used resampling filters include:

Filter Description
Box Simple and fast averaging filter appropriate for downscaling
Lanczos High-quality resampling filter for photographic images yielding sharp results
CatmullRom Sharp cubic filter that is faster than the Lanczos filter while providing similar results
MitchellNetravali Cubic filter that produces smoother results with less ringing artifacts than CatmullRom
Linear Bilinear resampling filter, produces smooth output, faster than cubic filters
NearestNeighbor Fastest resampling filter, no antialiasing

The default value is Box. You may override the default value in the site configuration.

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

See github.com/disintegration/imaging for the complete list of resampling filters. If you wish to improve image quality at the expense of performance, you may wish to experiment with the alternative filters.

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 Crop "250x250 center" />}}

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

This is the shortcode used to generate the examples above:

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

Call the shortcode from your Markdown like this:

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

{{% note %}} Note the self-closing shortcode syntax above. You may call the imgproc shortcode with or without inner content. {{% /note %}}

Imaging Configuration

Processing Options

Define an imaging section in your site configuration to set the default image processing options.

{{< code-toggle file="config" copy=true >}} [imaging] resampleFilter = "Box" quality = 75 hint = "photo" anchor = "Smart" bgColor = "#ffffff" {{< /code-toggle >}}

anchor
See image processing options: anchor.
bgColor
See image processing options: background color.
hint
See image processing options: hint.
quality
See image processing options: quality.
resampleFilter
See image processing options: resampling filter.

Exif Data

Define an imaging.exif section in your site configuration to control the availability of Exif data.

{{< code-toggle file="config" copy=true >}} [imaging.exif] includeFields = "" excludeFields = "" disableDate = false disableLatLong = false {{< /code-toggle >}}

disableDate
Hugo extracts the image creation date/time into .Date. Set this to true to disable. Default is false.
disableLatLong
Hugo extracts the GPS latitude and longitude into .Lat and .Long. Set this to true to disable. Default is false.
excludeFields
Regular expression matching the Exif tags to exclude from the .Tags collection. Default is "".
includeFields
Regular expression matching the Exif tags to include in the .Tags collection. Default is "". To include all available tags, set this value to ".*".

{{% note %}} To improve performance and decrease cache size, if you set neither excludeFields nor includeFields, Hugo excludes the following tags: ColorSpace, Contrast, Exif, Exposure[M|P|B], Flash, GPS, JPEG, Metering, Resolution, Saturation, Sensing, Sharp, and WhiteBalance. {{% /note %}}

Smart Cropping of Images

By default, Hugo uses the Smartcrop library when cropping images with the Crop orFill methods. You can set the anchor point manually, but in most cases the Smart option will make a good choice.

Examples using the sunset image from above:

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

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

Image Processing Performance Consideration

Hugo caches processed images in the resources directory. If you include this directory in source control, Hugo will not have to regenerate the images in a CI/CD workflow (e.g., GitHub Pages, GitLab Pages, Netlify, etc.). This results in faster builds.

If you change image processing methods or options, or if you rename or remove images, the resources directory will contain unused images. To remove the unused images, perform garbage collection with:

hugo --gc