Home / Gatsby Js / Gatsby – Working with Images

Gatsby – Working with Images

Gatsby is an awesome open source framework based on React. By using Gatsby we can build ⚡️ fast websites and apps. Gatsby provides the easiest way to develop, build and deploy your apps through the command line. Gatsby provides a great plugin to handle image compression and much more functionality that impresses you.

Working with Images

Gatsby provides the gatsby-image plugin. This plugin uses the advanced image loading techniques to easily and completely optimize image loading for your sites.

Features provided by gatsby-image

  • Resizing large images that needs your design
  • Auto generating multiple small images that need for smartphone and tablets
  • Auto Optimize all the loaded images
  • Efficiently lazy-loading images to speed initial page load and save bandwidth
  • Use the Blur-up technique
  • Hold the image position so your page doesn’t jump while the images load

Lets start to install the gatsby-image plugin and its related dependencies.

npm install --save gatsby-image gatsby-transformer-sharp gatsby-plugin-sharp

The gatsby-image plugin uses two more plugins to provide better result to load images they are gatsby-transformer-sharp and gatsby-plugin-sharp.

Now we have to load these dependencies to gatsby-config.js file:

plugins: [`gatsby-transformer-sharp`, `gatsby-plugin-sharp`]

Also make sure you have setup the source plugin, so your images are available in graphql queries.

const path = require(`path`)

module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: path.join(__dirname, `src`, `images`),
      },
    },
    `gatsby-plugin-sharp`,
    `gatsby-transformer-sharp`,
  ],
}

This is how we can use the image:

import React from "react"
import { graphql } from "gatsby"
import Img from "gatsby-image"

export default ({ data }) => (
  <div>
    <h1>Hello gatsby-image</h1>
    <Img fixed={data.file.childImageSharp.fixed} />
  </div>
)

export const query = graphql`
  query {
    file(relativePath: { eq: "images/slider_1.jpeg" }) {
      childImageSharp {
        # Specify the image processing specifications right in the query.
        # Makes it trivial to update as your page's design changes.
        fixed(width: 125, height: 125) {
          ...GatsbyImageSharpFixed
        }
      }
    }
  }
`