diff --git a/packages/gatsby-plugin-sharp/src/__tests__/__snapshots__/index.js.snap b/packages/gatsby-plugin-sharp/src/__tests__/__snapshots__/index.js.snap index c3c9665cfb044..4394102f521c3 100644 --- a/packages/gatsby-plugin-sharp/src/__tests__/__snapshots__/index.js.snap +++ b/packages/gatsby-plugin-sharp/src/__tests__/__snapshots__/index.js.snap @@ -70,67 +70,15 @@ Object { } `; -exports[`gatsby-plugin-sharp queueImageResizing should process immediately when asked 1`] = ` -[MockFunction] { - "calls": Array [ - Array [ - Object { - "args": Object { - "base64": true, - "duotone": false, - "grayscale": false, - "jpegProgressive": true, - "maxWidth": 800, - "pathPrefix": "", - "pngCompressionLevel": 9, - "pngCompressionSpeed": 4, - "quality": 50, - "sizeByPixelDensity": false, - "toFormat": "png", - "width": 3, - }, - "inputPath": "/packages/gatsby-plugin-sharp/src/__tests__/images/144-density.png", - "outputPath": "/public/static/1234/39ca0/test.png", - }, - Object { - "addThirdPartySchema": [Function], - "createJob": [Function], - "createNode": [Function], - "createNodeField": [Function], - "createPage": [Function], - "createPageDependency": [Function], - "createParentChildLink": [Function], - "createRedirect": [Function], - "deleteComponentsDependencies": [Function], - "deleteNode": [Function], - "deleteNodes": [Function], - "deletePage": [Function], - "endJob": [Function], - "replaceComponentQuery": [Function], - "replaceStaticQuery": [Function], - "replaceWebpackConfig": [Function], - "setBabelOptions": [Function], - "setBabelPlugin": [Function], - "setBabelPreset": [Function], - "setJob": [Function], - "setPluginStatus": [Function], - "setWebpackConfig": [Function], - "touchNode": [Function], - }, - Object { - "defaultQuality": 50, - "lazyImageGeneration": true, - "stripMetadata": true, - "useMozJpeg": false, - }, - ], - ], - "results": Array [ - Object { - "type": "return", - "value": Promise {}, - }, - ], +exports[`gatsby-plugin-sharp stats determines if the image is transparent, based on the presence and use of alpha channel 1`] = ` +Object { + "isTransparent": false, +} +`; + +exports[`gatsby-plugin-sharp stats determines if the image is transparent, based on the presence and use of alpha channel 2`] = ` +Object { + "isTransparent": true, } `; diff --git a/packages/gatsby-plugin-sharp/src/__tests__/images/alphatest.png b/packages/gatsby-plugin-sharp/src/__tests__/images/alphatest.png new file mode 100755 index 0000000000000..9780f66bcd5cd Binary files /dev/null and b/packages/gatsby-plugin-sharp/src/__tests__/images/alphatest.png differ diff --git a/packages/gatsby-plugin-sharp/src/__tests__/index.js b/packages/gatsby-plugin-sharp/src/__tests__/index.js index 93d52c9a1e30a..95abe56c7d9fc 100644 --- a/packages/gatsby-plugin-sharp/src/__tests__/index.js +++ b/packages/gatsby-plugin-sharp/src/__tests__/index.js @@ -17,6 +17,7 @@ const { fixed, queueImageResizing, getImageSize, + stats, } = require(`../`) const { scheduleJob } = require(`../scheduler`) scheduleJob.mockResolvedValue(Promise.resolve()) @@ -391,6 +392,21 @@ describe(`gatsby-plugin-sharp`, () => { expect(result).toMatchSnapshot() }) }) + + describe(`stats`, () => { + it(`determines if the image is transparent, based on the presence and use of alpha channel`, async () => { + const result = await stats({ file, args }) + expect(result).toMatchSnapshot() + expect(result.isTransparent).toEqual(false) + + const alphaResult = await stats({ + file: getFileObject(path.join(__dirname, `images/alphatest.png`)), + args, + }) + expect(alphaResult).toMatchSnapshot() + expect(alphaResult.isTransparent).toEqual(true) + }) + }) }) function getFileObject(absolutePath, name = `test`) { diff --git a/packages/gatsby-plugin-sharp/src/index.js b/packages/gatsby-plugin-sharp/src/index.js index fd54db62f42d8..f6b0090f7d5ae 100644 --- a/packages/gatsby-plugin-sharp/src/index.js +++ b/packages/gatsby-plugin-sharp/src/index.js @@ -261,6 +261,24 @@ async function getTracedSVG({ file, options, cache, reporter }) { return undefined } +async function stats({ file, reporter }) { + let imgStats + try { + imgStats = await sharp(file.absolutePath).stats() + } catch (err) { + reportError( + `Failed to get stats for image ${file.absolutePath}`, + err, + reporter + ) + return null + } + + return { + isTransparent: !imgStats.isOpaque, + } +} + async function fluid({ file, args = {}, reporter, cache }) { const options = healOptions(getPluginOptions(), args, file.extension) @@ -572,3 +590,4 @@ exports.resolutions = fixed exports.fluid = fluid exports.fixed = fixed exports.getImageSize = getImageSize +exports.stats = stats diff --git a/packages/gatsby-remark-images/README.md b/packages/gatsby-remark-images/README.md index f5783f499ce65..be5f4835768d0 100644 --- a/packages/gatsby-remark-images/README.md +++ b/packages/gatsby-remark-images/README.md @@ -44,19 +44,20 @@ plugins: [ ## Options -| Name | Default | Description | -| ---------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `maxWidth` | `650` | The `maxWidth` in pixels of the div where the markdown will be displayed. This value is used when deciding what the width of the various responsive thumbnails should be. | -| `linkImagesToOriginal` | `true` | Add a link to each image to the original image. Sometimes people want to see a full-sized version of an image e.g. to see extra detail on a part of the image and this is a convenient and common pattern for enabling this. Set this option to false to disable this behavior. | -| `showCaptions` | `false` | Add a caption to each image with the contents of the title attribute, when this is not empty. If the title attribute is empty but the alt attribute is not, it will be used instead. Set this option to true to enable this behavior. You can also pass an array instead to specify which value should be used for the caption — for example, passing `['alt', 'title']` would use the alt attribute first, and then the title. When this is set to `true` it is the same as passing `['title', 'alt']`. If you just want to use the title (and omit captions for images that have alt attributes but no title), pass `['title']`. | -| `markdownCaptions` | `false` | Parse the caption as markdown instead of raw text. Ignored if `showCaptions` is `false`. | -| `sizeByPixelDensity` | `false` | Analyze images' pixel density to make decisions about target image size. This is what GitHub is doing when embedding images in tickets. This is a useful setting for documentation pages with a lot of screenshots. It can have unintended side effects on high pixel density artworks.

Example: A screenshot made on a retina screen with a resolution of 144 (e.g. Macbook) and a width of 100px, will be rendered at 50px. | -| `wrapperStyle` | | Add custom styles to the div wrapping the responsive images. Use the syntax for the style attribute e.g. `margin-bottom:10px; background: red;` or a function returning a style string which receives the information about the image you can use to dynamically set styles based on the aspectRatio for example. | -| `backgroundColor` | `white` | Set the background color of the image to match the background image of your design.

**Note:**
- set this option to `transparent` for a transparent image background.
- set this option to `none` to completely remove the image background. | -| `quality` | `50` | The quality level of the generated files. | -| `withWebp` | `false` | Additionally generate WebP versions alongside your chosen file format. They are added as a srcset with the appropriate mimetype and will be loaded in browsers that support the format. Pass `true` for default support, or an object of options to specifically override those for the WebP files. For example, pass `{ quality: 80 }` to have the WebP images be at quality level 80. | -| `tracedSVG` | `false` | Use traced SVGs for placeholder images instead of the "blur up" effect. Pass `true` for traced SVGs with the default settings (seen [here][3]), or an object of options to override the defaults. For example, pass `{ color: "#F00", turnPolicy: "TURNPOLICY_MAJORITY" }` to change the color of the trace to red and the turn policy to TURNPOLICY_MAJORITY. See [`node-potrace` parameter documentation][4] for a full listing and explanation of the available options. | -| `loading` | `lazy` | Set the browser's native lazy loading attribute. One of `lazy`, `eager` or `auto`. | +| Name | Default | Description | +| ----------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `maxWidth` | `650` | The `maxWidth` in pixels of the div where the markdown will be displayed. This value is used when deciding what the width of the various responsive thumbnails should be. | +| `linkImagesToOriginal` | `true` | Add a link to each image to the original image. Sometimes people want to see a full-sized version of an image e.g. to see extra detail on a part of the image and this is a convenient and common pattern for enabling this. Set this option to false to disable this behavior. | +| `showCaptions` | `false` | Add a caption to each image with the contents of the title attribute, when this is not empty. If the title attribute is empty but the alt attribute is not, it will be used instead. Set this option to true to enable this behavior. You can also pass an array instead to specify which value should be used for the caption — for example, passing `['alt', 'title']` would use the alt attribute first, and then the title. When this is set to `true` it is the same as passing `['title', 'alt']`. If you just want to use the title (and omit captions for images that have alt attributes but no title), pass `['title']`. | +| `markdownCaptions` | `false` | Parse the caption as markdown instead of raw text. Ignored if `showCaptions` is `false`. | +| `sizeByPixelDensity` | `false` | Analyze images' pixel density to make decisions about target image size. This is what GitHub is doing when embedding images in tickets. This is a useful setting for documentation pages with a lot of screenshots. It can have unintended side effects on high pixel density artworks.

Example: A screenshot made on a retina screen with a resolution of 144 (e.g. Macbook) and a width of 100px, will be rendered at 50px. | +| `wrapperStyle` | | Add custom styles to the div wrapping the responsive images. Use the syntax for the style attribute e.g. `margin-bottom:10px; background: red;` or a function returning a style string which receives the information about the image you can use to dynamically set styles based on the aspectRatio for example. | +| `backgroundColor` | `white` | Set the background color of the image to match the background image of your design.

**Note:**
- set this option to `transparent` for a transparent image background.
- set this option to `none` to completely remove the image background. | +| `quality` | `50` | The quality level of the generated files. | +| `withWebp` | `false` | Additionally generate WebP versions alongside your chosen file format. They are added as a srcset with the appropriate mimetype and will be loaded in browsers that support the format. Pass `true` for default support, or an object of options to specifically override those for the WebP files. For example, pass `{ quality: 80 }` to have the WebP images be at quality level 80. | +| `tracedSVG` | `false` | Use traced SVGs for placeholder images instead of the "blur up" effect. Pass `true` for traced SVGs with the default settings (seen [here][3]), or an object of options to override the defaults. For example, pass `{ color: "#F00", turnPolicy: "TURNPOLICY_MAJORITY" }` to change the color of the trace to red and the turn policy to TURNPOLICY_MAJORITY. See [`node-potrace` parameter documentation][4] for a full listing and explanation of the available options. | +| `loading` | `lazy` | Set the browser's native lazy loading attribute. One of `lazy`, `eager` or `auto`. | +| `disableBgImageOnAlpha` | `false` | Images containing transparent pixels around the edges results in images with blurry edges. As a result, these images do not work well with the "blur up" technique used in this plugin. As a workaround to disable background images with blurry edges on images containing transparent pixels, enable this setting. | ## dynamic wrapperStyle example diff --git a/packages/gatsby-remark-images/src/__tests__/__snapshots__/index.js.snap b/packages/gatsby-remark-images/src/__tests__/__snapshots__/index.js.snap index 3735c3fccd366..57cddbf372e30 100644 --- a/packages/gatsby-remark-images/src/__tests__/__snapshots__/index.js.snap +++ b/packages/gatsby-remark-images/src/__tests__/__snapshots__/index.js.snap @@ -1,5 +1,63 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`disableBgImageOnAlpha disables background image on transparent images when disableBgImageOnAlpha === true 1`] = ` +" + + + \\"some + + " +`; + +exports[`disableBgImageOnAlpha does not disable background image on transparent images when disableBgImageOnAlpha === false 1`] = ` +" + + + \\"some + + " +`; + exports[`it handles goofy nesting properly 1`] = ` " { }) }, traceSVG: mockTraceSVG, + stats() { + return Promise.resolve({ + isTransparent: true, + }) + }, } }) @@ -587,3 +592,33 @@ describe(`markdownCaptions`, () => { expect($(`figcaption`).length).toBe(0) }) }) + +describe(`disableBgImageOnAlpha`, () => { + it(`does not disable background image on transparent images when disableBgImageOnAlpha === false`, async () => { + const imagePath = `images/my-image.jpeg` + const content = `![some alt](./${imagePath} "some title")` + + const nodes = await plugin(createPluginOptions(content, imagePath), { + disableBgImageOnAlpha: false, + }) + expect(nodes.length).toBe(1) + + const node = nodes.pop() + expect(node.type).toBe(`html`) + expect(node.value).toMatchSnapshot() + }) + + it(`disables background image on transparent images when disableBgImageOnAlpha === true`, async () => { + const imagePath = `images/my-image.jpeg` + const content = `![some alt](./${imagePath} "some title")` + + const nodes = await plugin(createPluginOptions(content, imagePath), { + disableBgImageOnAlpha: true, + }) + expect(nodes.length).toBe(1) + + const node = nodes.pop() + expect(node.type).toBe(`html`) + expect(node.value).toMatchSnapshot() + }) +}) diff --git a/packages/gatsby-remark-images/src/constants.js b/packages/gatsby-remark-images/src/constants.js index c426bca1dc186..4563717aaafdf 100644 --- a/packages/gatsby-remark-images/src/constants.js +++ b/packages/gatsby-remark-images/src/constants.js @@ -8,6 +8,7 @@ exports.DEFAULT_OPTIONS = { withWebp: false, tracedSVG: false, loading: `lazy`, + disableBgImageOnAlpha: false, } exports.imageClass = `gatsby-resp-image-image` diff --git a/packages/gatsby-remark-images/src/index.js b/packages/gatsby-remark-images/src/index.js index 8606c741d70f8..289f7e1d7a89e 100644 --- a/packages/gatsby-remark-images/src/index.js +++ b/packages/gatsby-remark-images/src/index.js @@ -10,7 +10,7 @@ const path = require(`path`) const queryString = require(`query-string`) const isRelativeUrl = require(`is-relative-url`) const _ = require(`lodash`) -const { fluid, traceSVG } = require(`gatsby-plugin-sharp`) +const { fluid, stats, traceSVG } = require(`gatsby-plugin-sharp`) const Promise = require(`bluebird`) const cheerio = require(`cheerio`) const slash = require(`slash`) @@ -282,10 +282,20 @@ module.exports = ( const imageCaption = options.showCaptions && getImageCaption(node, overWrites) + let removeBgImage = false + if (options.disableBgImageOnAlpha) { + const imageStats = await stats({ file: imageNode, reporter }) + if (imageStats && imageStats.isTransparent) removeBgImage = true + } + + const bgImage = removeBgImage + ? `` + : ` background-image: url('${placeholderImageData}'); background-size: cover;` + let rawHTML = ` ${imageTag} `.trim()