How to load pictures in Gatsby?

1, How does the Gatsby page load pictures?

When writing website pages, you will always encounter pictures to display, so how to load these pictures?

1. There are three types of pictures in Gatsby:
  • Local images, such as images in src/images directory;

  • Remote network pictures, such as: https://learn-anything.cn/static/cf1d0cf910dcc988ea869d56609eca53/096ec/bainian.webp

  • The picture node in the Gatsby data layer.

2, Load local and network pictures

Under Gatsby, images are loaded through the StaticImage component.

1,StaticImage
  • Install plug-ins

    npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem
    
  • Add configuration

    // gatsby-config.js
    module.exports = {
      siteMetadata: {
        title: "My First Gatsby Site",
      },
      plugins: [
        "gatsby-plugin-image",
        "gatsby-plugin-sharp",
      ],
    };
    
  • display picture

    StaticImage is a component provided by Gatsby plugin image. It is similar to the img tag in html and can be used directly in the page.

    import * as React from 'react'
    import Layout from '../components/layout'
    import { StaticImage } from 'gatsby-plugin-image'
    import bainian from "../images/bainian.jpg"
    
    const IndexPage = () => {
        return (
            <Layout pageTitle="Home Page">
                <p>I'm making this by following the Gatsby Tutorial.</p>
                <StaticImage
                    alt="Network picture"
                    src="https://learn-anything.cn/static/cf1d0cf910dcc988ea869d56609eca53/096ec/bainian.webp"
                />
                <StaticImage
                    alt="Local picture"
                    src="../images/bainian.jpg"
                />
          			<img alt="img Show local pictures" src={bainian} />
            </Layout>
        )
    }
    
    export default IndexPage
    
2. StaticImage and img
  • The difference between < img / > and < StaticImage / > is that the StaticImage component preprocesses the image and selects the appropriate resolution for image rendering according to different displays. There is no need to download the original image, which speeds up the display speed and saves network traffic.

  • < img / > usage examples in gatsby:

    import React from "react"
    import logo from "./logo.png" // Here tell Webpack that the JS file uses this picture
    console.log(logo) // /logo.84287d09.png
    function Header() {
      // What you get is your picture URL
      return <img src={logo} alt="Logo" />
    }
    export default Header
    
3. borderRadius failure

As follows, use borderRadius in style to add rounded borders to the picture. This method will fail in safari browser.

<StaticImage src="../images/bainian.jpg" alt="Bainian toothpaste" style={{border: 'solid 1px #ddd', borderRadius: 10}}/>

Solution: use imgStyle instead of style.

<StaticImage src="../images/bainian.jpg" alt="Bainian toothpaste" imgStyle={{border: 'solid 1px #ddd', borderRadius: 10}}/>
3, Load data layer picture node

The data layer picture node is called dynamic picture. When the project is started, gatsby will automatically download pictures from the source data and convert them into picture nodes in the data layer. The process of picture file - > data layer picture node is explained in detail below.

1. Principle description:
  • The local file is converted to the data layer node allFile through the Gatsby source filesystem plug-in;

  • The image node in the data layer node allFile is converted to the data layer node ImageSharp through the Gatsby transformer sharp plug-in;

  • Use Graphql to query the ImageSharp node data and pass it to the component GatsbyImage provided by the Gatsby plugin image plug-in for display.

  • [note]: the Gatsby transformer sharp plug-in will add an ImageSharp picture node to the image attribute of all data layer nodes. For example, the Gatsby source strapi plug-in obtains data from strapi to generate an allStrapiArticles node, and Gatsby transformer sharp will automatically generate a picture node for its image attribute: image.localFile.childImageSharp

4, Display data layer picture node
1. Example description

There are src/mdx/my-first-post.mdx files and Src / mdx / Christopher Ayme OCZ files in the gatsby project-_ Y7-ptg-unsplash.jpg picture, write a page to display its data and pictures.

// src/mdx/my-first-post.mdx
---
title: "My First Post"
date: "2021-07-23"
hero_image: "./christopher-ayme-ocZ-_Y7-Ptg-unsplash.jpg"
hero_image_alt: "A gray pitbull relaxing on the sidewalk with its tongue hanging out"
hero_image_credit_text: "Christopher Ayme"
hero_image_credit_link: "https://unsplash.com/photos/ocZ-_Y7-Ptg"
---

This is my first blog post! Isn't it *great*?
Some of my **favorite** things are:
* Petting dogs
* Singing
* Eating potato-based foods
2. Solution
  • Step 1: convert the. MDX file into an MDX data node and install the following plug-ins

    npm install gatsby-source-filesystem gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react gatsby-transformer-sharp gatsby-plugin-image
    
  • Step 2: modify the configuration in gatsby-config.js

    // gatsby-config.js
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `posts`,
            path: `${__dirname}/src/mdx/`,
          },
        },
        {
          resolve: `gatsby-plugin-mdx`,
          options: {
            extensions: [`.mdx`, `.md`]
          },
        },
        "gatsby-transformer-sharp",
        "gatsby-plugin-image"
      ],
    }
    
  • Step 3: create a new page src/pages/first-post.js. The name of the page comes from the slug attribute (mdx routing rule) of the mdx node corresponding to the. Mdx file.

    import * as React from 'react'
    import { graphql } from 'gatsby'
    import { MDXRenderer } from 'gatsby-plugin-mdx'
    import { GatsbyImage, getImage } from 'gatsby-plugin-image'
    
    const BlogPost = ({ data }) => {
    
      console.log("BlogPost :", data);
      const image = getImage(data.mdx.frontmatter.hero_image)
    
      return (
        <div >
          <p>Title: {data.mdx.frontmatter.title}</p>
          <p>Posted: {data.mdx.frontmatter.date}</p>
          <GatsbyImage
            image={image}
            alt={data.mdx.frontmatter.hero_image_alt}
          />
          <MDXRenderer>
            {data.mdx.body}
          </MDXRenderer>
        </div>
      )
    }
    
    export const query = graphql`
        query($id: String) {
          mdx(id: {eq: $id}) {
            body
            frontmatter {
              title
              hero_image_alt
              hero_image_credit_link
              hero_image_credit_text
              hero_image {
                childImageSharp {
                  gatsbyImageData
                }
              }
            }
          }
        }
      `
    
    export default BlogPost
    
  • Step 4: browser access: http://localhost:8000/first-blog, view the page, display pictures and. mdx content.

5, Displays the pictures contained in the strapi
1. Problem description

Strapi is a visual CMS (content management system). The documents edited by markdown can be easily stored in strapi, and RestApi access data is provided. How to access data in strapi in gatsby?

2. Solution

With the help of the plug-in gatsby source strapi, the data in strapi is transformed into gatsby data nodes for easy access.

  • Step 1: convert the articles data in strapi into gatsby data nodes, and install the following plug-ins

    npm install gatsby-source-strapi gatsby-transformer-sharp gatsby-plugin-image
    
  • Step 2: modify the configuration in gatsby-config.js

    // gatsby-config.js
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-strapi`,
          options: {
            // apiURL: "http://localhost:1337",
            queryLimit: 1000,
            collectionTypes: [`articles`],
          },
        },
        "gatsby-transformer-sharp",
        "gatsby-plugin-image"
      ],
    }
    
  • Step 3: create a new page Src / pages / home.js

    import * as React from "react"
    import { graphql } from "gatsby"
    import { GatsbyImage } from "gatsby-plugin-image"
    
    const HomePage = ({ data }) => {
        return (
            <GatsbyImage image={data.strapiArticles.image.localFile.childImageSharp.gatsbyImageData} />
        )
    }
    
    export default HomePage
    
    export const query = graphql`{
        strapiArticles {
            image {
              localFile {
                childImageSharp {
                  gatsbyImageData
                }
              }
            }
          }
      }
    `
    
  • Step 4: browser access: http://localhost:8000/homepage , view content

6, Reference documents

Posted on Thu, 02 Dec 2021 23:15:22 -0500 by donnierivera