hugo

Fork of github.com/gohugoio/hugo with reverse pagination support

git clone git://git.shimmy1996.com/hugo.git

index.md (15651B)

    1 ---
    2 title: "Image Processing"
    3 description: "Resize, crop, rotate, filter, and convert images."
    4 date: 2018-01-24T13:10:00-05:00
    5 categories: ["content management"]
    6 keywords: [resources, images]
    7 weight: 4004
    8 draft: false
    9 toc: true
   10 menu:
   11   docs:
   12     parent: "content-management"
   13     weight: 32
   14 ---
   15 ## Image Resources
   16 
   17 To process an image, you must access the image as either a page resource or a global resource.
   18 
   19 ### Page Resources
   20 
   21 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.
   22 
   23 ```text
   24 content/
   25 └── posts/
   26     └── post-1/           <-- page bundle
   27         ├── index.md
   28         └── sunset.jpg    <-- page resource
   29 ```
   30 
   31 To access an image as a page resource:
   32 
   33 ```go-html-template
   34 {{ $image := .Resources.GetMatch "sunset.jpg" }}
   35 ```
   36 
   37 ### Global Resources
   38 
   39 A global resource is a file:
   40 
   41 - Within the `assets` directory, or
   42 - Within any directory [mounted] to the `assets` directory, or
   43 - Located on a remote server accessible via `http` or `https`
   44 
   45 ```text
   46 assets/
   47 └── images/
   48     └── sunset.jpg    <-- global resource
   49 ```
   50 
   51 To access a local image as a global resource:
   52 
   53 ```go-html-template
   54 {{ $image := resources.Get "images/sunset.jpg" }}
   55 ```
   56 
   57 To access a remote image as a global resource:
   58 
   59 ```go-html-template
   60 {{ $image := resources.GetRemote "https://gohugo.io/img/hugo-logo.png" }}
   61 ```
   62 
   63 ## Image Rendering
   64 
   65 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.
   66 
   67 Example 1: Throws an error if the resource is not found.
   68 
   69 ```go-html-template
   70 {{ $image := .Resources.GetMatch "sunset.jpg" }}
   71 <img src="{{ $image.RelPermalink }}" width="{{ $image.Width }}" height="{{ $image.Height }}">
   72 ```
   73 
   74 Example 2: Skips image rendering if the resource is not found.
   75 
   76 ```go-html-template
   77 {{ $image := .Resources.GetMatch "sunset.jpg" }}
   78 {{ with $image }}
   79   <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
   80 {{ end }}
   81 ```
   82 
   83 Example 3: A more concise way to skip image rendering if the resource is not found.
   84 
   85 ```go-html-template
   86 {{ with .Resources.GetMatch "sunset.jpg" }}
   87   <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
   88 {{ end }}
   89 ```
   90 
   91 ## Image Processing Methods
   92 
   93 The `image` resource implements the  `Resize`, `Fit`, `Fill`, `Crop`, `Filter`, and `Exif` methods.
   94 
   95 {{% note %}}
   96 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.
   97 {{% /note %}}
   98 
   99 ### Resize
  100 
  101 Resize an image to the specified width and/or height.
  102 
  103 If you specify both width and height, the resulting image will be disproportionally scaled unless the original image has the same aspect ratio.
  104 
  105 ```go-html-template
  106 {{/* Resize to a width of 600px and preserve aspect ratio */}}
  107 {{ $image := $image.Resize "600x" }}
  108 
  109 {{/* Resize to a height of 400px and preserve aspect ratio */}}
  110 {{ $image := $image.Resize "x400" }}
  111 
  112 {{/* Resize to a width of 600px and a height of 400px */}}
  113 {{ $image := $image.Resize "600x400" }}
  114 ```
  115 
  116 ### Fit
  117 
  118 Downscale an image to fit the given dimensions while maintaining aspect ratio. You must provide both width and height.
  119 
  120 ```go-html-template
  121 {{ $image := $image.Fit "600x400" }}
  122 ```
  123 
  124 ### Fill
  125 
  126 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.
  127 
  128 ```go-html-template
  129 {{ $image := $image.Fill "600x400" }}
  130 ```
  131 
  132 ### Crop
  133 
  134 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.
  135 
  136 ```go-html-template
  137 {{ $image := $image.Crop "600x400" }}
  138 ```
  139 
  140 ### Filter
  141 
  142 Apply one or more [filters] to an image.
  143 
  144 ```go-html-template
  145 {{ $image := $image.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}
  146 ```
  147 
  148 Write this in a more functional style using pipes. Hugo applies the filters in the order given.
  149 
  150 ```go-html-template
  151 {{ $image := $image | images.Filter (images.GaussianBlur 6) (images.Pixelate 8) }}
  152 ```
  153 
  154 Sometimes it can be useful to create the filter chain once and then reuse it.
  155 
  156 ```go-html-template
  157 {{ $filters := slice  (images.GaussianBlur 6) (images.Pixelate 8) }}
  158 {{ $image1 := $image1.Filter $filters }}
  159 {{ $image2 := $image2.Filter $filters }}
  160 ```
  161 
  162 ### Exif
  163 
  164 Provides an [Exif] object containing image metadata.
  165 
  166 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.
  167 
  168 ```go-html-template
  169 {{ with $image.Exif }}
  170   Date: {{ .Date }}
  171   Lat/Long: {{ .Lat }}/{{ .Long }}
  172   Tags:
  173   {{ range $k, $v := .Tags }}
  174     TAG: {{ $k }}: {{ $v }}
  175   {{ end }}
  176 {{ end }}
  177 ```
  178 
  179 You may also access Exif fields individually, using the [`lang.FormatNumber`] function to format the fields as needed.
  180 
  181 ```go-html-template
  182 {{ with $image.Exif }}
  183   <ul>
  184     {{ with .Date }}<li>Date: {{ .Format "January 02, 2006" }}</li>{{ end }}
  185     {{ with .Tags.ApertureValue }}<li>Aperture: {{ lang.FormatNumber 2 . }}</li>{{ end }}
  186     {{ with .Tags.BrightnessValue }}<li>Brightness: {{ lang.FormatNumber 2 . }}</li>{{ end }}
  187     {{ with .Tags.ExposureTime }}<li>Exposure Time: {{ . }}</li>{{ end }}
  188     {{ with .Tags.FNumber }}<li>F Number: {{ . }}</li>{{ end }}
  189     {{ with .Tags.FocalLength }}<li>Focal Length: {{ . }}</li>{{ end }}
  190     {{ with .Tags.ISOSpeedRatings }}<li>ISO Speed Ratings: {{ . }}</li>{{ end }}
  191     {{ with .Tags.LensModel }}<li>Lens Model: {{ . }}</li>{{ end }}
  192   </ul>
  193 {{ end }}
  194 ```
  195 
  196 #### Exif Variables
  197 
  198 .Date
  199 : Image creation date/time. Format with the [time.Format] function.
  200 
  201 .Lat
  202 : GPS latitude in degrees.
  203 
  204 .Long
  205 : GPS longitude in degrees.
  206 
  207 .Tags
  208 : 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).
  209 
  210 ## Image Processing Options
  211 
  212 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.
  213 
  214 ### Dimensions
  215 
  216 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.
  217 
  218 ```go-html-template
  219 {{ $image := $image.Resize "600x" }}
  220 {{ $image := $image.Resize "x400" }}
  221 {{ $image := $image.Resize "600x400" }}
  222 {{ $image := $image.Fit "600x400" }}
  223 {{ $image := $image.Fill "600x400" }}
  224 {{ $image := $image.Crop "600x400" }}
  225 ```
  226 
  227 ### Rotation
  228 
  229 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%:
  230 
  231 ```go-html-template
  232 {{ $image = $image.Resize "200x r90" }}
  233 ```
  234 
  235 In the example above, the width represents the desired width _after_ rotation.
  236 
  237 To rotate an image without scaling, use the dimensions of the original image:
  238 
  239 ```go-html-template
  240 {{ with .Resources.GetMatch "sunset.jpg" }}
  241   {{ with .Resize (printf "%dx%d r90" .Height .Width) }}
  242     <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
  243   {{ end }}
  244 {{ end }}
  245 ```
  246 
  247 In the example above, on the second line, we have reversed width and height to reflect the desired dimensions _after_ rotation.
  248 
  249 ### Anchor
  250 
  251 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`.
  252 
  253 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](#processing-options).
  254 
  255 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:
  256 
  257 ```go-html-template
  258 {{ $image.Crop "200x100 TopLeft" }}
  259 ```
  260 
  261 If you apply rotation when using the `Crop` or `Fill` method, specify the anchor relative to the rotated image.
  262 
  263 ### Target Format
  264 
  265 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`.
  266 
  267 ```go-html-template
  268 {{ $image.Resize "600x webp" }}
  269 ```
  270 
  271 To convert an image without scaling, use the dimensions of the original image:
  272 
  273 ```go-html-template
  274 {{ with .Resources.GetMatch "sunset.jpg" }}
  275   {{ with .Resize (printf "%dx%d webp" .Width .Height) }}
  276     <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}">
  277   {{ end }}
  278 {{ end }}
  279 ```
  280 
  281 ### Quality
  282 
  283 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.
  284 
  285 The default value is 75. You may override the default value in the [site configuration](#processing-options).
  286 
  287 ```go-html-template
  288 {{ $image.Resize "600x webp q50" }}
  289 ```
  290 
  291 ### Hint
  292 
  293 <!-- Specifies a libwebp preset, not a libwebp image hint. -->
  294 
  295 Applicable to WebP images, this option corresponds to a set of pre-defined encoding parameters.
  296 
  297 Value|Example
  298 :--|:--
  299 `drawing`|Hand or line drawing with high-contrast details
  300 `icon`|Small colorful image
  301 `photo`|Outdoor photograph with natural lighting
  302 `picture`|Indoor photograph such as a portrait
  303 `text`|Image that is primarily text
  304 
  305 The default value is `photo`. You may override the default value in the [site configuration](#processing-options).
  306 
  307 ```go-html-template
  308 {{ $image.Resize "600x webp picture" }}
  309 ```
  310 
  311 ### Background Color
  312 
  313 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.
  314 
  315 Use either a 3-digit or a 6-digit hexadecimal color code (e.g., `#00f` or `#0000ff`).
  316 
  317 The default value is `#ffffff` (white). You may override the default value in the [site configuration](#processing-options).
  318 
  319 ```go-html-template
  320 {{ $image.Resize "600x jpg #b31280" }}
  321 ```
  322 
  323 ### Resampling Filter
  324 
  325 You may specify the resampling filter used when resizing an image. Commonly used resampling filters include:
  326 
  327 Filter|Description
  328 :--|:--
  329 `Box`|Simple and fast averaging filter appropriate for downscaling
  330 `Lanczos`|High-quality resampling filter for photographic images yielding sharp results
  331 `CatmullRom`|Sharp cubic filter that is faster than the Lanczos filter while providing similar results
  332 `MitchellNetravali`|Cubic filter that produces smoother results with less ringing artifacts than CatmullRom
  333 `Linear`|Bilinear resampling filter, produces smooth output, faster than cubic filters
  334 `NearestNeighbor`|Fastest resampling filter, no antialiasing
  335 
  336 The default value is `Box`. You may override the default value in the [site configuration](#processing-options).
  337 
  338 ```go-html-template
  339 {{ $image.Resize "600x400 Lanczos" }}
  340 ```
  341 
  342 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.
  343 
  344 ## Image Processing Examples
  345 
  346 _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)_
  347 
  348 {{< imgproc sunset Resize "300x" />}}
  349 
  350 {{< imgproc sunset Fill "90x120 left" />}}
  351 
  352 {{< imgproc sunset Fill "90x120 right" />}}
  353 
  354 {{< imgproc sunset Fit "90x90" />}}
  355 
  356 {{< imgproc sunset Crop "250x250 center" />}}
  357 
  358 {{< imgproc sunset Resize "300x q10" />}}
  359 
  360 This is the shortcode used to generate the examples above:
  361 
  362 {{< code file="layouts/shortcodes/imgproc.html" >}}
  363 {{< readfile file="layouts/shortcodes/imgproc.html" >}}  
  364 {{< /code >}}
  365 
  366 Call the shortcode from your markdown like this:
  367 
  368 ```go-html-template
  369 {{</* imgproc sunset Resize "300x" /*/>}}
  370 ```
  371 
  372 {{% note %}}
  373 Note the self-closing shortcode syntax above. You may call the `imgproc` shortcode with or without **inner content**.
  374 {{% /note %}}
  375 
  376 ## Imaging Configuration
  377 
  378 ### Processing Options
  379 
  380 Define an `imaging` section in your site configuration to set the default [image processing options](#image-processing-options).
  381 
  382 {{< code-toggle file="config" copy=true >}}
  383 [imaging]
  384 resampleFilter = "Box"
  385 quality = 75
  386 hint = "photo"
  387 anchor = "Smart"
  388 bgColor = "#ffffff"
  389 {{< /code-toggle >}}
  390 
  391 anchor
  392 : See image processing options: [anchor](#anchor).
  393 
  394 bgColor
  395 : See image processing options: [background color](#background-color).
  396 
  397 hint
  398 : See image processing options: [hint](#hint).
  399 
  400 quality
  401 : See image processing options: [quality](#quality).
  402 
  403 resampleFilter
  404 : See image processing options: [resampling filter](#resampling-filter).
  405 
  406 ### Exif Data
  407 
  408 Define an `imaging.exif` section in your site configuration to control the availability of Exif data.
  409 
  410 {{< code-toggle file="config" copy=true >}}
  411 [imaging.exif]
  412 includeFields = ""
  413 excludeFields = ""
  414 disableDate = false
  415 disableLatLong = false
  416 {{< /code-toggle >}}
  417 
  418 disableDate
  419 : Hugo extracts the image creation date/time into `.Date`. Set this to `true` to disable. Default is `false`.
  420 
  421 disableLatLong
  422 : Hugo extracts the GPS latitude and longitude into `.Lat` and `.Long`. Set this to `true` to disable. Default is `false`.
  423 
  424 excludeFields
  425 : Regular expression matching the Exif tags to exclude from the `.Tags` collection. Default is&nbsp;`""`.
  426 
  427 includeFields
  428 : 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;`".*"`.
  429 
  430 {{% note %}}
  431 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`.
  432 {{% /note %}}
  433 
  434 ## Smart Cropping of Images
  435 
  436 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.
  437 
  438 Examples using the sunset image from above:
  439 
  440 {{< imgproc sunset Fill "200x200 smart" />}}
  441 
  442 {{< imgproc sunset Crop "200x200 smart" />}}
  443 
  444 ## Image Processing Performance Consideration
  445 
  446 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.
  447 
  448 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:
  449 
  450 ```bash
  451 hugo --gc
  452 ```
  453 
  454 [`anchor`]: {{< relref "content-management/image-processing#anchor" >}}
  455 [`lang.FormatNumber`]: {{< relref "functions/lang#langformatnumber" >}}
  456 [Exif]: <https://en.wikipedia.org/wiki/Exif>
  457 [filters]: {{< relref "functions/images" >}}
  458 [github.com/disintegration/imaging]: <https://github.com/disintegration/imaging#image-resizing>
  459 [mounted]: {{< relref "hugo-modules/configuration#module-config-mounts">}}
  460 [page bundle]: {{< relref "content-management/page-bundles" >}}
  461 [Smartcrop]: <https://github.com/muesli/smartcrop#smartcrop>
  462 [time.Format]: {{< relref "functions/dateformat" >}}