hugo/content/en/content-management/image-processing/index.md
Bjørn Erik Pedersen 00c4484c70 Squashed 'docs/' changes from 392668f4f..32cb8785e
32cb8785e Fix page weights in content management section (#1896)
11977b96f Make relURL and related functions consistent (#1895)
f12180207 Clarify github deployment (#1894)
958877789 Remove remaining references to Highlight.js (#1893)
fc487d263 Minor edit to taxonomy page
3b6a224b2 Update theme
b28553b62 Change "flavor" to "edition" when referring to builds (#1892)
660e7581c Replaced sudo in OpenBSD with doas (#1891)
e3fcdea10 fix a few minor grammatical issues on Firebase docs (#1889)
e4c8b30eb update Static Web Apps docs (#1890)
da2197c9e Update hosting-on-firebase.md (#1347)
5f2a0c271 Adding deployment guide for Azure Static Web Apps (#1456)
5aaf570cd add Azure Static Web App config to 404 template
35fc54362 add Azure Static Web App config to 404 template
d48f67ba1 Update 01-flavors.md
11debae8d Cleaned Use of ref and relref section, added refs of index.md and _in… (#1744)
b77604078 docs: Add link to menu entry variables (#1827)
0fa8a6bf0 Misc copy edits (#1887)
c27b545ac Improve explanation of safeHTMLAttr's function (#1503)
b04a4b32e Make CLI command summaries meaningful (#1886)
dbf00a81f Fix a typo in diagrams documentation (#1885)
11f884327 docs: Clarify how to remove draft/future/expired content (#1831)
6dc9e9860 Improve complement function (#1884)
56448a51a Remove erroneous sourcemap desc (#1883)
a0d0d2829 Merge branch 'divinerites-patch-1'
10f20cb5e Add a plausible-hugo theme component
9f1413eb5 Minor edits to showcase example
7d78420db fix broken link to Isso Comments
925cb291f Make directory tree consistent with other examples
300fff092 Add link to security policy from getenv.md (#1746)
7b4c517a6 Fix docs menu weights
ce35775e0 Update faq.md (#1763)
f3fb791a4 Remove dated new-in flags (#1879)
b6c634629 Remove deprecated templating langs (#1880)
1b25ca34f Update the findRE and replaceRE functions (#1881)
28757ec73 Add Alora Labs website to showcase (#1494)
e3c4bc4e7 Remove unimplemented "ugly" property
86afd84ff Update editors.md (#1878)
44c093911 Add urlquery function docs (#1633)
16a8c3548 Update links to installation page (#1876)
9e357f078 Add missing sections to BSD installation page (#1875)
1b1291634 Promote "Installation" to a section
9dd51235b Add detail to description of .Plain page variable (#1870)
d333d0287 Minor markdown linting fix and URL updates (#1873)
d57c8aa50 Remove extraneous apostrophe (#1871)
8c25cfc5c Update index.md
09fea41e0 Add lang to fenced code block
35b904798 Add small documentation about .Site.Social.twitter variable (#1854)
672042f89 Consolidate site configuration
dfd4dd873 Add help.ampio.com showcase. (#1863)
e8d0e7bdf Include link to internal templates code (#1794)
7db6f0c01 Add example to split function (#1867)
be87dba80 Clarify split function docs (#1792)
a079193f1 Fix typo on data templates page
b234c70ee Fix data templates page (#1855)
074232b45 Update front-matter.md (#1856)
711c8fa80 Added missing default value (#1862)
034762882 Fixed some grammar issues and typos (#1865)
764574a4d Fix spelling error
2698f2d44 update URLs to prevent redirects (#1864)
68f05fdc8 Fenced code blocks should have a language specified (#1861)
24393315b GitHub Workflows security hardening (#1859)
3eeee13bf Markdown formatting: Add Fenced code block languages (#1858)
e152cdf1f netlify: Hugo 0.105.0
4c7fc9f7e Merge branch 'tempv0.105.0'
d16710afc Change anchor reference to use relref function calls (#1853)
f52af8e4a tpl/encoding: Add noHTMLEscape option to jsonify
eca0046c4 Update hosting-on-keycdn docs (#1852)
ffbe17a48 Add note for rsync deploy command (#1415)
c482133f1 docs: Update quick start to clarify the need of extended version (#1828)
1e3b33804 use correct URL for Google Search console verification (#1851)
dac034f63 Markdown and formatting fixes (#1850)
43f177e3c Fix LiveReload in quick-start (#1739)
f78deaa5f Add link for ''Hugo Shortcode Syntax Highlighting' VS Code extension (#1765)
08087ecd7 Remove some hidden pages (#1848)
b6cb5ae48 Markdown linting fixes (#1846)
527ec5941 Update hugo.md (#1742)
83e8f2168 Clarify that a shortcode with .Inner must be closed (#1785)
4193f4445 Add Super Linter GitHub Action (#1845)
fd91bfe1a Formatting and grammar fixes (#1844)
ab5a49c49 Create codeql-analysis GitHub Action (#1812)
63b3e082e Add tutorial on using fusejs to search examples (#1756)
54c253ab0 Note that Google Universal Analytics are deprecated (#1770)
385fa77c6 Update articles.toml (#1840)
5e336bd26 Replace awkward wording (ESL?) (#1842)
2446ad349 Added Introduction to Hugo tutorial/video series (#1736)
7b21b2e76 Don't use self-closing generator tag
ef73712ff Image processing. available methods: add method 'Colors' (#1837)
018f83bbe [comment platform] - add new alternative (#1751)
5636c208b Grammar and spelling fixes (#1836)
3f2e26f77 Change link of repojacking vulnerable link - JekyllToHugo (#1834)
301379fc3 fix: use shorter image URL to make it easier to read (#1835)
de5fa7b30 Update search.md to include Pagefind (#1826)
e9d72bcda Breadcrumb example: add basic accessibility (#1832)
6cffff87a netlify: Hugo 0.104.3
892360f61 Update output-formats.md
09a7a46ae Remove my defunct and little used migrator (#1824)
347434cca netlify: Hugo 0.104.2
f8c721162 Update postcss.md
c2baf7155 netlify: Hugo 0.104.1
05d1192cd Update diagrams.md (#1823)
3c43a8bbe netlify: Hugo 0.104.0
57973b334 Merge branch 'tempv0.104.0'
da775a36d docs: Regen docs helper
ae48b5901 docs: Regenerate CLI docs
af4a823b1 resources/images: Add $image.Colors
8e3f9ca64 Remove outdated IE conditional comments example (#1821)
d1a84701b fix typo in template introduction (#1820)
c0c7339e0 Update internal.md
17aefc515 Remove the recommendation about where to put the GA tempalte
263297236 Adjust GA template instructions
1cc265d99 Update the GA template usage section
e11968338 config/security: Allow proxy variables in subcommands
9218ab993 netlify: Hugo 0.103.1
0b0e890d1 Update markdownify and RenderString documentation (#1818)
50f5d4776 Fix internal link (#1817)
6beb443c5 netlify: Hugo 0.103.0
14b5af248 Merge branch 'tempv0.103.0'
548e7aa62 server: Add 404 support
3a20aa0ba Update theme

git-subtree-dir: docs
git-subtree-split: 32cb8785ea74d5b82f2e2bea79d059cab497902a
2022-11-17 16:14:29 +01:00

477 lines
16 KiB
Markdown

---
title: Image Processing
linkTitle: Image Processing
description: Resize, crop, rotate, filter, and convert images.
categories: [content management]
keywords: [resources, images]
menu:
docs:
parent: content-management
weight: 90
toc: true
weight: 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.
```text
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`
```text
assets/
└── images/
└── sunset.jpg <-- global resource
```
To access a local image as a global resource:
```go-html-template
{{ $image := resources.Get "images/sunset.jpg" }}
```
To access a remote image as a global resource:
```go-html-template
{{ $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.
```go-html-template
{{ $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.
```go-html-template
{{ $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.
```go-html-template
{{ 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.
```go-html-template
{{/* 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.
```go-html-template
{{ $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.
```go-html-template
{{ $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.
```go-html-template
{{ $image := $image.Crop "600x400" }}
```
### Filter
Apply one or more [filters] to an image.
```go-html-template
{{ $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.
```go-html-template
{{ $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.
```go-html-template
{{ $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.
```go-html-template
{{ $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.
```go-html-template
{{ 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.
```go-html-template
{{ 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](#exif-data).
## 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.
```go-html-template
{{ $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%:
```go-html-template
{{ $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:
```go-html-template
{{ 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:
```go-html-template
{{ $image.Crop "200x100 TopLeft" }}
```
If you apply [rotation](#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`.
```go-html-template
{{ $image.Resize "600x webp" }}
```
To convert an image without scaling, use the dimensions of the original image:
```go-html-template
{{ 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].
```go-html-template
{{ $image.Resize "600x webp q50" }}
```
### Hint
<!-- Specifies a libwebp preset, not a libwebp image 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].
```go-html-template
{{ $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].
```go-html-template
{{ $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].
```go-html-template
{{ $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](https://commons.wikimedia.org/wiki/User:Bep) (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:
```go-html-template
{{</* 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](#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](#anchor).
bgColor
: See image processing options: [background color](#background-color).
hint
: See image processing options: [hint](#hint).
quality
: See image processing options: [quality](#quality).
resampleFilter
: See image processing options: [resampling filter](#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&nbsp;`""`.
includeFields
: Regular expression matching the Exif tags to include in the `.Tags` collection. Default is&nbsp;`""`. To include all available tags, set this value to&nbsp;`".*"`.
{{% 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` or`Fill` 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:
```bash
hugo --gc
```
[`anchor`]: {{< relref "content-management/image-processing#anchor" >}}
[`lang.FormatNumber`]: {{< relref "functions/lang#langformatnumber" >}}
[Exif]: <https://en.wikipedia.org/wiki/Exif>
[filters]: {{< relref "functions/images" >}}
[github.com/disintegration/imaging]: <https://github.com/disintegration/imaging#image-resizing>
[mounted]: {{< relref "hugo-modules/configuration#module-config-mounts">}}
[page bundle]: {{< relref "content-management/page-bundles" >}}
[Smartcrop]: <https://github.com/muesli/smartcrop#smartcrop>
[time.Format]: {{< relref "functions/dateformat" >}}
[`Colors`]: #colors
[`Crop`]: #crop
[`Exif`]: #exif
[`Fill`]: #fill
[`Filter`]: #filter
[`Fit`]: #fit
[`Resize`]: #resize
[site configuration]: #processing-options
[`with`]: /functions/with/