hugo/docs/content/en/content-management/image-processing/index.md

318 lines
9.9 KiB
Markdown
Raw Normal View History

---
title: "Image Processing"
description: "Image Page resources can be resized and cropped."
date: 2018-01-24T13:10:00-05:00
linktitle: "Image Processing"
categories: ["content management"]
keywords: [resources, images]
weight: 4004
draft: false
toc: true
menu:
docs:
parent: "content-management"
weight: 32
---
## The Image Page Resource
Squashed 'docs/' changes from 54f0e8776..bd0e15bb6 bd0e15bb6 Optimised images with calibre/image-actions 59830ea44 Remove comments from quickstart code samples 348821b5d Remove image-actions 1cbbd26a9 Update index.md bcf3de764 Update index.md fcf17e6ef Release 0.62.1 0956bde21 Merge branch 'temp621' 28d604756 releaser: Add release notes to /docs for release of 0.62.1 c895f12e7 Fix statement about version installed with apt-get (#854) e96928e38 Updated quickstart to split theme download and theme config add into separate blocks (#967) e099c1ad6 changed ".Title" to ".URL" (#972) bea71280d Fix small typing error (#1001) 9c28c422e Correct hyperlink for 'markdownify' function cf3844a06 Corrected small conjugation mistake (#996) 8b9c1d4f2 Added remarks about additional parameters in ref/relref (#995) ca06c9a56 Fix illegal character in render-link.html example 7a85c789b Update RenderString.md 69df3b17e Update configuration-markup.md 43e9222a2 Revert "Add shortcodes to note comparing with `markdownify`" 2bd5bc2d7 Add shortcodes to note comparing with `markdownify` ddfee60b7 Update configuration-markup.md f87c35fe2 docs: Remove extra double quotation 5ca5cc15f Update index.md 6e457f5ec Update configuration-markup.md 12df3c0fc Update configuration-markup.md 91977fd96 Update configuration-markup.md 377b8954a Update configuration-markup.md 99d691b5e Update hosting-on-render.md ccf855b22 Update index.md a945acc42 Update index.md 7d4f308d6 Fix Netlify config f4caa07f5 Release 0.62.0 79d18276f releaser: Add release notes to /docs for release of 0.62.0 9db1a08d1 Merge commit '8a4005cf2b0ef34265ff8051a6b76226685fc226' 79e556223 docs: More on hooks 5088c54df tpl: Do not return any value in errorf 98c8c8638 tpl: Add a warnf template func 4a9d76cea docs: Regen docshelper 626e53b55 Fix incorrect MIME type from image/jpg to image/jpeg f92f77c5d Preserve HTML Text for link render hooks 6db9c52b1 docs: Footnote 16801db3b Add render template hooks for links and images 0facb823c Merge commit '2e711a28c71e8667258e5ab824f9b9a71c261b0a' 79bf8ed4c markup/tableofcontents: Add config option for ordered list git-subtree-dir: docs git-subtree-split: bd0e15bb6063f7ad4f0c47eb33c8c0c23c962d13
2020-01-05 10:13:09 +00:00
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" >}}):
```go-html-template
{{ 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 methods `Resize`, `Fit` and `Fill`, each returning the transformed image using the specified dimensions and processing options. The `image` resource also, since Hugo 0.58, implements the method `Exif` and `Filter`.
### Resize
Resizes the image to the specified width and height.
```go
// 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.
```go
{{ $image := $resource.Fit "600x400" }}
```
### Fill
Resize and crop the image to match the given dimensions. Both height and width are required.
```go
{{ $image := $resource.Fill "600x400" }}
```
### Filter
Apply one or more filters to your image. See [Image Filters](/functions/images/#image-filters) for a full list.
```go-html-template
{{ $img = $img.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}
```
The above can also be written in a more functional style using pipes:
```go-html-template
{{ $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:
```go-html-template
{{ $filters := slice (images.GaussianBlur 6) (images.Pixelate 8) }}
{{ $img1 = $img1.Filter $filters }}
{{ $img2 = $img2.Filter $filters }}
```
### Exif
Provides an [Exif](https://en.wikipedia.org/wiki/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.:
```go-html-template
{{ with $img.Exif }}
Date: {{ .Date }}
Lat/Long: {{ .Lat}}/{{ .Long }}
Tags:
{{ range $k, $v := .Tags }}
TAG: {{ $k }}: {{ $v }}
{{ end }}
Squashed 'docs/' changes from 51c4f3184..af4b7ac5b af4b7ac5b Remove mention of Amber and Ace c841e9207 Exif docs corrections (#978) 0f82420b8 Change cache assets default example to 1 year 676dc6e12 Release 0.61.0 a1d9fb18a Merge commit '79c5d7053486f540b6219e693d5590f2c4c3937a' 1b9e675cd releaser: Add release notes to /docs for release of 0.61.0 5b95cbc8a Fixed suffixIsRemoved error in code samples (#975) 59b2c245b Fix Usage section in toc.md to consider Goldmark TOC settings fd3828673 Add link on how to configure TOC w/ Goldmark ea339f2d6 Added external learning resources including Hugo In Action book. fab502d5d Adjust release notes 269a025ef Release 0.60.1 6bff50bea Merge branch 'temp601' e15251c43 releaser: Add release notes to /docs for release of 0.60.1 690b864b9 Update use-modules.md 345ca8c36 Update syntax-highlighting.md be64af9f5 Update syntax-highlighting.md df9dead83 Update syntax-highlighting.md 1c6e6d238 Fix relnotes 0ea6b2012 Update homepagetweets.toml 2c465625d Update index.md 0025bba09 Update index.md 7417f1c05 Update index.md 9eeb8ce57 Release 0.60.0 25a711023 Merge branch 'temp60' 0c4faab0e releaser: Add release notes to /docs for release of 0.60.0 779e5108e Update installing.md 2ef1c386a Minor text improvements in README.md 41ec5a19a Reword sentence for clarity search.md ded74f098 Add Goldmark as the new default markdown handler cb55cdbb0 Update introduction.md fcaad653a Update homepage.md 7427a1fc5 Update configuration.md 8cc2c72ca tpl/collections: Allow dict to create nested structures 4538c092c Merge commit 'efc0b1bb6c6564f54d596467dbc6a18cb206954e' 90f908e7b Support Go time format strings in permalinks git-subtree-dir: docs git-subtree-split: af4b7ac5b403e392a92228e66058331905fff7dc
2019-12-15 09:35:09 +00:00
{{ end }}
```
Squashed 'docs/' changes from 341ecabb2..988f7d5c2 988f7d5c2 Document default `enableInlineShortcodes` value 0f604a345 Fix typo in 0.66.0 release note 26fc74fe3 How to access individual EXIF data tags d5d3bad9a Fix localhost links fa6921213 Update index.md 5bf558f78 Release 0.66.0 74ccdaaf5 Merge branch 'temp660' 75faa478b releaser: Add release notes to /docs for release of 0.66.0 c4a4a9922 docs: Regen CLI docs 0624ac198 Add build.UseResourceCacheWhen 58a8d7cd1 Add build options documentation d926c595e fix typo 99713d44b resources: Add basic @import support to resources.PostCSS 224b96cf7 deploy: Implement include/exclude filters for deploy eb1a00050 Adjusting description; WordPress with capitalized P 91d8efa22 Add another tool for migration from the Wordpress a6938a4ac Adjust showcase description a9c0a0a69 Adjust showcase e5af08aa6 Adding Aether as a proposed showcase item. 0013daa34 Add hugo.IsProduction function 34c419ef3 tpl: Add math.Sqrt 5bdab0ebd Update minification.md 9039332e2 Hugo 0.65.3 1400caf3a Merge branch 'temp653' 9796bb337 releaser: Add release notes to /docs for release of 0.65.3 65b26598f Fix typo 23aa57d80 Fix crashes for 404 in IsAncestor etc. 42c54bc6c 0.65.2 67fd5c1f6 Merge branch 'temp652' d820ac017 releaser: Add release notes to /docs for release of 0.65.2 51f0888ff Release 0.65.1 91e95260c releaser: Add release notes to /docs for release of 0.65.1 1880ebf05 fix broken link on internal.md ffaa33889 Update migrations.md de4d64675 Another tool for migration from Medium platform 90b178d77 releaser: Add release notes to /docs for release of 0.65.1 6925cda30 Handle corner case with rendering text as code in URL 3cb4b19dd Release 0.65.0 7a600cb99 Merge branch 'temp650' ef9531ff6 releaser: Add release notes to /docs for release of 0.65.0 9bc19606f docs: Regenerate CLI docs d4a886ed2 Add Page.GetTerms a3bf273a5 fix broken link on use-modules.md 001f52f4e Fix mage URL in development.md eef72e887 Merge commit '4b670bc8cc38103c2c60e5090c2f56bf30832b8d' b18a76631 commands: Support "hugo mod get -u ./..." git-subtree-dir: docs git-subtree-split: 988f7d5c2d7a1d40ec2c8ab961cb5a4e41b5bd4c
2020-03-09 19:19:32 +00:00
Or individually access EXIF data with dot access, e.g.:
```go-html-template
{{ 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>
Squashed 'docs/' changes from 341ecabb2..988f7d5c2 988f7d5c2 Document default `enableInlineShortcodes` value 0f604a345 Fix typo in 0.66.0 release note 26fc74fe3 How to access individual EXIF data tags d5d3bad9a Fix localhost links fa6921213 Update index.md 5bf558f78 Release 0.66.0 74ccdaaf5 Merge branch 'temp660' 75faa478b releaser: Add release notes to /docs for release of 0.66.0 c4a4a9922 docs: Regen CLI docs 0624ac198 Add build.UseResourceCacheWhen 58a8d7cd1 Add build options documentation d926c595e fix typo 99713d44b resources: Add basic @import support to resources.PostCSS 224b96cf7 deploy: Implement include/exclude filters for deploy eb1a00050 Adjusting description; WordPress with capitalized P 91d8efa22 Add another tool for migration from the Wordpress a6938a4ac Adjust showcase description a9c0a0a69 Adjust showcase e5af08aa6 Adding Aether as a proposed showcase item. 0013daa34 Add hugo.IsProduction function 34c419ef3 tpl: Add math.Sqrt 5bdab0ebd Update minification.md 9039332e2 Hugo 0.65.3 1400caf3a Merge branch 'temp653' 9796bb337 releaser: Add release notes to /docs for release of 0.65.3 65b26598f Fix typo 23aa57d80 Fix crashes for 404 in IsAncestor etc. 42c54bc6c 0.65.2 67fd5c1f6 Merge branch 'temp652' d820ac017 releaser: Add release notes to /docs for release of 0.65.2 51f0888ff Release 0.65.1 91e95260c releaser: Add release notes to /docs for release of 0.65.1 1880ebf05 fix broken link on internal.md ffaa33889 Update migrations.md de4d64675 Another tool for migration from Medium platform 90b178d77 releaser: Add release notes to /docs for release of 0.65.1 6925cda30 Handle corner case with rendering text as code in URL 3cb4b19dd Release 0.65.0 7a600cb99 Merge branch 'temp650' ef9531ff6 releaser: Add release notes to /docs for release of 0.65.0 9bc19606f docs: Regenerate CLI docs d4a886ed2 Add Page.GetTerms a3bf273a5 fix broken link on use-modules.md 001f52f4e Fix mage URL in development.md eef72e887 Merge commit '4b670bc8cc38103c2c60e5090c2f56bf30832b8d' b18a76631 commands: Support "hugo mod get -u ./..." git-subtree-dir: docs git-subtree-split: 988f7d5c2d7a1d40ec2c8ab961cb5a4e41b5bd4c
2020-03-09 19:19:32 +00:00
{{ 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
Squashed 'docs/' changes from 51c4f3184..af4b7ac5b af4b7ac5b Remove mention of Amber and Ace c841e9207 Exif docs corrections (#978) 0f82420b8 Change cache assets default example to 1 year 676dc6e12 Release 0.61.0 a1d9fb18a Merge commit '79c5d7053486f540b6219e693d5590f2c4c3937a' 1b9e675cd releaser: Add release notes to /docs for release of 0.61.0 5b95cbc8a Fixed suffixIsRemoved error in code samples (#975) 59b2c245b Fix Usage section in toc.md to consider Goldmark TOC settings fd3828673 Add link on how to configure TOC w/ Goldmark ea339f2d6 Added external learning resources including Hugo In Action book. fab502d5d Adjust release notes 269a025ef Release 0.60.1 6bff50bea Merge branch 'temp601' e15251c43 releaser: Add release notes to /docs for release of 0.60.1 690b864b9 Update use-modules.md 345ca8c36 Update syntax-highlighting.md be64af9f5 Update syntax-highlighting.md df9dead83 Update syntax-highlighting.md 1c6e6d238 Fix relnotes 0ea6b2012 Update homepagetweets.toml 2c465625d Update index.md 0025bba09 Update index.md 7417f1c05 Update index.md 9eeb8ce57 Release 0.60.0 25a711023 Merge branch 'temp60' 0c4faab0e releaser: Add release notes to /docs for release of 0.60.0 779e5108e Update installing.md 2ef1c386a Minor text improvements in README.md 41ec5a19a Reword sentence for clarity search.md ded74f098 Add Goldmark as the new default markdown handler cb55cdbb0 Update introduction.md fcaad653a Update homepage.md 7427a1fc5 Update configuration.md 8cc2c72ca tpl/collections: Allow dict to create nested structures 4538c092c Merge commit 'efc0b1bb6c6564f54d596467dbc6a18cb206954e' 90f908e7b Support Go time format strings in permalinks git-subtree-dir: docs git-subtree-split: af4b7ac5b403e392a92228e66058331905fff7dc
2019-12-15 09:35:09 +00:00
Date
: "photo taken" date/time
Lat
: "photo taken where", GPS latitude
Long
: "photo taken where", GPS longitude
See [Image Processing Config](#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 `#`.
```go
{{ $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](#image-processing-config).
### JPEG Quality
Only relevant for JPEG images, values 1 to 100 inclusive, higher is better. Default is 75.
```go
{{ $image.Resize "600x q50" }}
```
### 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](https://github.com/golang/go/issues/4341) of JPEG images.
```go
{{ $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](https://github.com/muesli/smartcrop) to determine the best crop.
```go
{{ $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.
```go
{{ $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`.
```go
{{ $image.Resize "600x jpg" }}
```
## 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 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:
```go-html-template
{{</* 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:
```toml
[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 quality setting. Default is 75.
quality = 75
# 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 the [Smartcrop](https://github.com/muesli/smartcrop), a library created by [muesli](https://github.com/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:
```bash
hugo --gc
```
{{% note %}}
**GC** is short for **Garbage Collection**.
{{% /note %}}