Switch branches/tags
AnushPatel-patch-1 JanoshRiebesell-patch-1 KyleAMathews-patch-1 LekoArts-patch-1 Partner-program add-depn add-escalade-sports-case-study add-mobile-performance-post add-plugin-documentation alter-blog-post-date amberleyromo-7730-starter-showcase-sourcing amberleyromo-patch-1 array-doclets berrak-responsive-layout calcsam-patch-1 ccustom-algolia-index change-hacktoberfest-title config-api coreyward-patch-1-1 cypress-timeouts docs-rename-starter docs/gatsby-remark-images-sharp documentation-project-blogpost-new-title drop-alpha-support filter-css fix-broken-link fix-doc fix/starter-detail-dependency-grid fix/typescript-reach-router fixes-to-plugin-library gatsby-ssr-silent-fail graphql-filter-sort gvarandas-patch-1 hu0p-patch-1 imagentleman-patch-1 link-container m-allanson-patch-1 marisamorby-swag-store-post master neo/move-prefixPath old-master-3 old-master-4 old-master-6 old-master-7 page-metadata-splitting plugin-blogpost-edit plugin-cli pr/8963 revert-4254-blog-documentation-project revert-5047-update-remark revert-workspaces rfbotto-patch-1 sample-branch-example sebastienfi-wp-orderby-date-asc sharp-images-no-ext sort-chunks starterShowcase2 style-guide-update styled-components-babelrc-config-doc test-builds topics/gatsby-plugin-sharp-tracesvg-fluid topics/inconsistent-accordian-behavior-docs-sidebar topics/using-gatsby-image-design-refresh topics/www-bump-remark-autolink-headers topics/www-sidebar-move-expand-all-down tryzniak-patch-1 update-imagemin-deps v1 v2 valse-disable-default-pageview valse-resolve-env worker
Nothing to show
Find file History
DSchau chore(release): Publish
 - gatsby-plugin-offline@2.0.19
 - gatsby-plugin-sharp@2.0.15
 - gatsby-source-contentful@2.0.19
 - gatsby-transformer-sqip@2.0.10
 - gatsby@2.0.64
 - graphql-skip-limit@2.0.3
Latest commit 11afc1b Dec 7, 2018

README.md

gatsby-plugin-sharp

Exposes several image processing functions built on the Sharp image processing library. This is a low-level helper plugin generally used by other Gatsby plugins. You generally shouldn't be using this directly but might find it helpful if doing very custom image processing.

It aims to provide excellent out-of-the box settings for processing common web image formats.

For JPEGs it generates progressive images with a default quality level of 50.

For PNGs it uses pngquant to compress images. By default it uses a quality setting of [50-75].

Install

npm install --save gatsby-plugin-sharp

How to use

// In your gatsby-config.js
plugins: [
  {
    resolve: `gatsby-plugin-sharp`,
    options: {
      useMozJpeg: false,
      stripMetadata: true,
    },
  },
]

Methods

resize

Parameters

  • width (int, default: 400)
  • height (int)
  • quality (int, default: 50)
  • jpegProgressive (bool, default: true)
  • pngCompressionLevel (int, default: 9)
  • base64(bool, default: false)

Returns

  • src (string)
  • width (int)
  • height (int)
  • aspectRatio (float)

fixed

Automatically create sizes for different resolutions — we do 1x, 1.5x, 2x, and 3x.

Parameters

  • width (int, default: 400)
  • height (int)
  • quality (int, default: 50)

Returns

  • base64 (string)
  • aspectRatio (float)
  • width (float)
  • height (float)
  • src (string)
  • srcSet (string)

fluid

Create fluid sizes (in width) for the image. If the max width of the container for the rendered markdown file is 800px, the sizes would then be: 200, 400, 800, 1200, 1600, 2400 – enough to provide close to the optimal image size for every device size / screen resolution.

If you want more control over which sizes are output you can use the srcSetBreakpoints parameter. For example, if you want images that are 200, 340, 520, and 890 wide you can add srcSetBreakpoints: [ 200, 340, 520, 890 ] as a parameter. You will also get maxWidth as a breakpoint (which is 800 by default), so you will actually get [ 200, 340, 520, 800, 890 ] as breakpoints.

On top of that, fluid returns everything else (namely aspectRatio and a base64 image to use as a placeholder) you need to implement the "blur up" technique popularized by Medium and Facebook (and also available as a Gatsby plugin for Markdown content as gatsby-remark-images).

Parameters

  • maxWidth (int, default: 800)
  • maxHeight (int)
  • quality (int, default: 50)
  • sizeByPixelDensity (bool, default: false)
  • srcSetBreakpoints (array of int, default: [])

Returns

  • base64 (string)
  • aspectRatio (float)
  • src (string)
  • srcSet (string)
  • srcSetType (string)
  • sizes (string)
  • originalImg (string)

Shared Options

In addition to their individual parameters, all methods above share the following:

  • grayscale (bool, default: false)
  • duotone (bool|obj, default: false)
  • toFormat (string, default: '')
  • cropFocus (string, default: 'sharp.strategy.attention')

toFormat

Convert the source image to one of the following available options: NO_CHANGE, JPG, PNG, WEBP.

cropFocus

Change the cropping focus. Available options: CENTER, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST, NORTHWEST, ENTROPY, ATTENTION. See Sharp's crop.

rotate

Rotate the image (after cropping). See Sharp's rotate.

grayscale

Uses Sharp's greyscale to convert the source image to 8-bit greyscale, 256 shades of grey, e.g.

allImageSharp {
  edges {
    node {
      ... on ImageSharp {
        resize(width: 150, height: 150, grayscale: true) {
          src
        }
      }
    }
  }
}

duotone

Applys a "duotone" effect (see I, II, III) to the source image if given two hex colors shadow and highlight defining start and end color of the duotone gradient, e.g.

fixed(
  width: 800,
  duotone: {
    highlight: "#f00e2e",
    shadow: "#192550"
  }
) {
  src
  srcSet
  base64
}

the source image colors will be converted to match a gradient color chosen based on each pixel's relative luminance.
Logic is borrowed from react-duotone.

You can pass a third optional parameter, opacity:

fluid(
  width: 800,
  duotone: {
    highlight: "#f00e2e",
    shadow: "#192550",
    opacity: 50
  }
) {
  src
  srcSet
  base64
}

If set, a semi-transparent version of duotone'd image will be composited over the original image, allowing the original image and its colors to partially "shine through". Heads up: If the original image contains an alpha channel it will be flattened before creating the composite.

This works by adding an alpha channel to the duotone'd image - then we let Sharp do its magic via overlayWith; quoting the Sharp documentation:

If the overlay image contains an alpha channel then composition with premultiplication will occur.

tracedSVG

Generates a traced SVG of the image (see the original GitHub issue) and returns the SVG as "optimized URL-encoded" data: URI. It it used in gatsby-image to provide an alternative to the default inline base64 placeholder image.

Uses node-potrace and SVGO under the hood. Default settings for node-potrace:

  {
    color: `lightgray`,
    optTolerance: 0.4,
    turdSize: 100,
    turnPolicy: TURNPOLICY_MAJORITY,
  }

All node-potrace Potrace parameters are exposed and can be set via the traceSVG argument:

fixed(
  traceSVG: {
    color: "#f00e2e"
    turnPolicy: TURNPOLICY_MINORITY
    blackOnWhite: false
  }
) {
  src
  srcSet
  tracedSVG
}

Using MozJPEG

You can opt-in to use MozJPEG for jpeg-encoding. MozJPEG provides even better image compression than the default encoder used in gatsby-plugin-sharp. However, when using MozJPEG the build time of your Gatsby project will increase significantly.

To enable MozJPEG, you can set the useMozJpeg plugin option to true in gatsby-config.js.

For backwards compatible reasons, if useMozJpeg is not defined in the plugin options, the environment variable GATSBY_JPEG_ENCODER acts as a fallback if set to MOZJPEG:

GATSBY_JPEG_ENCODER=MOZJPEG

EXIF and ICC metadata

By default, gatsby-plugin-sharp strips all EXIF, ICC and other metadata present in your source file. This is the recommended default as it leads to smaller file sizes.

However, in situations where you wish to preserve EXIF metadata or ICC profiles (example: you are building a photography portfolio and wish to conserve the color profile or the copyright information of the photos you've exported from Adobe Lightroom or Phase One's Capture One), you can set the stripMetadata plugin option to false in gatsby-config.js.

It is important to note that if stripMetadata is set to false, all metadata information will be preserved from the source image, including but not limited to the latitude/longitude information of where the picture was taken (if present). If you wish to strip this information from the source file, you can either leave stripMetadata to its default of true, or manually pre-process your images with a tool such as ExifTool.