gatsby_使用gatsby-image(不含GraphQL)提供远程优化的图像

gatsby

Part 1 of this series chronicles the process of using remote images from Cloudinary in GatsbyJS projects through GraphQL queries. Here in part 2, you’ll learn how to —

本系列的第1部分介绍了通过GraphQL查询在GatsbyJS项目中使用Cloudinary的远程图像的过程。 在第2部分中,您将学习如何-

  • Leverage remote images stored in Cloudinary and served through an optimized content delivery network (CDN).

    利用存储在Cloudinary中并通过优化的内容交付网络(CDN)提供服务的远程映像。
  • Serve fluid or fixed images with gatsby-image.

    使用gatsby图像为流体图像或固定图像服务。
  • Render images for responsiveness and optimize them with gatsby-image.

    渲染图像以提高响应速度,并使用gatsby-image对其进行优化。
  • Transform those images with Cloudinary.

    使用Cloudinary转换这些图像。

For instance, we can quickly change this penguin image:

例如,我们可以快速更改此企鹅图像:

Specifically, this part guides you through two processes:

具体来说,本部分将指导您完成两个过程:

  1. Fetch an image from Cloudinary with the getFluidImageObject API of gatsby-transformer-cloudinary and render that image with gatsby-image. You can fetch any image from your Cloudinary account. Also, even after applying the Cloudinary transformations that you specify, the API can still optimize that image with gatsby-image during the build process.

    This image-fetching process requires no GraphQL queries.

    使用gatsby-transformer-cloudinary的getFluidImageObject API从Cloudinary获取图像,并使用gatsby-image渲染该图像。 您可以从Cloudinary帐户中获取任何图像。 此外,即使在应用您指定的Cloudinary转换之后,API仍可以在构建过程中使用gatsby-image优化该图像。

    此图像获取过程不需要GraphQL查询。

2. Create a user interface and typography with Chakra UI.

2 。 使用Chakra UI创建用户界面和版式。

初步步骤 ( Preliminary Steps )

Before you start, you must have installed Gatsby.js with npm on your system. See the Installation section in Part 1 for details.

开始之前,您必须在系统上安装了带有npm的Gatsby.js。 有关详细信息,请参见第1部分中的“安装”部分。

Also, create a new GatsbyJS project with the default GatsbyJS starter. Type:

另外,使用默认的GatsbyJS启动器创建一个新的GatsbyJS项目。 类型:

gatsby new gtc-demo-2

Alternatively, clone this branch of the project described in part 1.

或者, 克隆第1部分中描述的项目的此分支

设置项目配置 ( Setup of Project Configurations )

If you haven’t done it yet, follow the steps in the three subsections under Setup of Project Configurations in Part 1 to—

如果尚未执行此操作,请按照第1部分中 的“项目配置的设置”下的三个小节中的步骤操作,以便-

  1. Create a Cloudinary account.

    创建一个Cloudinary帐户。
  2. Set up gatsby-config.js.

    设置gatsby-config.js。
  3. Add environment variables.

    添加环境变量。

页面布局设计 ( Design of Page Layout )

You’re now ready to create a webpage and its layout.

现在,您可以创建网页及其布局了。

First, start a development environment by typing this command:

首先,通过键入以下命令来启动开发环境:

gatsby develop

Afterward, copy over the files in the components and pages directories of the project in part 1.

然后,复制第1部分中项目的component和pages目录中的文件。

使用getFluidImageObject和getFixedImageObject API进行图像获取 ( Image Fetching With getFluidImageObject and getFixedImageObject APIs )

Even though both getfluidImageObject and getFixedImageObject fetch images from Cloudinary accounts with multiple or chained transformations, the two APIs vary as follows:

即使getfluidImageObjectgetFixedImageObject都通过多重转换或链式转换从Cloudinary帐户中获取图像,这两个API也会如下变化:

getFluidImageObject returns fluid images with the breakpoints that you specified and, if you did not specify any, it returns breakpoints with the maximum width of 650.

getFluidImageObject返回具有指定断点的流体图像,如果未指定任何断点,则返回最大宽度为650的断点。

getFixedImageObject returns fixed-width images, passing them from the asynchronous calls of the functions to the fluid or fixed property of the gatsby-image <Image/> component.

getFixedImageObject返回固定宽度的图像,将它们从函数的异步调用传递到gatsby-image <Image/>组件的fluidfixed属性。

Both APIs fetch images with a single asynchronous operation, hence no need for GraphQL queries.

两种API均通过单个异步操作获取图像,因此无需GraphQL查询。

创建包含单个图像的网页 ( Creation of a Webpage That Contains a Single Image )

Now create a webpage that contains an image fetched with getFluidImageObject. Apply the same layout from part 1.

现在创建一个网页,其中包含用getFluidImageObject获取的图像。 应用第1部分中的相同布局。

By default, gatsby-transformer-cloudinary optimizes the quality and format of images through the f_auto and q_auto Cloudinary transformation parameters.

默认情况下,gatsby-transformer-cloudinary通过f_autoq_auto Cloudinary转换参数来优化图像的质量和格式。

GatsbyJS builds pages from the JavaScript (JS) files in the src/pages directory.

GatsbyJS使用src / pages目录中JavaScript(JS)文件构建页面。

Do the following:

请执行下列操作:

  1. Create a JS file titled single.js in src/pages. GatsbyJS adds single.js to the route /single.

    src/pages创建一个名为single.js的JS文件。 GatsbyJS增加single.js到路由/single

  2. Import the required modules into single.js with this code:

    使用以下代码将所需的模块导入single.js:

import React, { useEffect, useState } from "react"
import Layout from "../components/layout"
import SEO from "../components/seo"
import { getFluidImageObject } from "gatsby-transformer-cloudinary"
import Image from "gatsby-image"
import { Box, Heading, Text } from "@chakra-ui/core/dist";

3. Create and export a functional component titled SinglePage. In the function, fetch a single Cloudinary image with a public ID of your choice. Below is the code, in which the public ID is gatsby-source-cloudinary/penguin:

3 。 创建并导出名为SinglePage的功能组件。 在函数中,获取具有您选择的公共ID的单个Cloudinary映像。 下面是代码,其中公共ID为gatsby-source-cloudinary/penguin

const SinglePage = () => {
    const [fluid, setFluid] = useState(false);

    useEffect(() => {
        async function getData() {
            const res = await getFluidImageObject({
                public_id: "gatsby-source-cloudinary/penguin",
                cloudName: 'chuloo',
                originalHeight: 400,
                originalWidth: 500,
                transformations: ["e_replace_color:purple", "a_hflip"],
            });
            setFluid(res);
        }

        getData();


    }, []);

    return (
        <Layout>
            <SEO title={"single"}/>
            <Box>
                <Heading as={'h1'} size={'lg'} m={5} textAlign={'center'}>Single Fluid Image</Heading>
                <Box maxWidth={[350, 400, 500]} mx={"auto"} shadow="md" borderWidth="1px" rounded={'lg'} p={3}>
                    {fluid ? <Image fluid={fluid}/> : "loading..."}
                </Box>
                <Box my={30}>
                    <Text>This is a single image sourced directly from Cloudinary. This image can be any image in your
                        Cloudinary account, the public ID of the image is required to source this images for use in
                        gatsby-image </Text>
                </Box>

            </Box>
        </Layout>
    )
};

export default SinglePage

In the above code, getFluidImageObject is an asynchronous function, which is called on page load through useEffect. Once that function returns the image, you store it in the component’s fluid state with useState.

在上面的代码中, getFluidImageObject是一个异步函数,在页面加载时通过useEffect进行useEffect 。 该函数返回图像后,可使用useState将其存储在组件的fluid状态中。

Next, you pass the following keys to getFluidImageObjects in its object argument:

接下来,将以下键传递给其对象参数中的getFluidImageObjects:

  • public_id: The public ID of the Cloudinary image

    public _ id :Cloudinary映像的公共ID

  • cloudName: The cloud name of your Cloudinary account

    cloudName :您的Cloudinary帐户的云名称

  • originalHeight: The height of the image to be fetched

    originalHeight :要获取的图像的高度

  • originalWidth: The width of the image to be fetched

    originalWidth :要获取的图像的宽度

  • transformations: The transformations Cloudinary applies to the returned image

    转换 :Cloudinary转换适用于返回的图像

See the complete keys along with their optional and required arguments.

请参阅完整的键以及它们的可选和必需参数。

getFluidImageObject passes transformations in the transformation’s key to add a purple effect and to horizontally flip the image with the e_replace_color:purple and a_hflip parameters Cloudinary transformations respectively.

getFluidImageObject在转换键中传递转换,以添加紫色效果并分别使用e_replace_color:purplea_hflip parameters Cloudinary转换水平翻转图像。

With getFluidImageObjects, you can fetch with gatsby-image any image in your Cloudinary account for display on the page.

使用getFluidImageObjects,您可以使用gatsby-image获取Cloudinary帐户中的任何图像以显示在页面上。

The image looks like this before transformation:

After transformation, it looks like this:

转换前的图像如下所示:

转换后,它看起来像这样:

gatsby-image lazy-loads images that are sourced with getFluidImageObject.

gatsby-image延迟加载以getFluidImageObject来源的图像。

更新首页 (Update of Homepage)

Finally, add a button to the homepage for navigating to the image that you just sourced. To accomplish that task, edit the IndexPage component in the src/pages/index.js file to read as follows:

最后,在首页上添加一个按钮,以导航到您刚获取的图像。 要完成该任务,请编辑src/pages/index.js文件中的IndexPage组件,内容如下:

import React from "react"
import { graphql, Link, useStaticQuery } from "gatsby";
import Layout from "../components/layout"
import SEO from "../components/seo"
import Image from "gatsby-image"
import { Box, Button, Heading, Text } from "@chakra-ui/core/dist";

const IndexPage = () => {
    // fetch images
    const data = useStaticQuery(graphql`query BannerImage {
      bannerImage: file(name: { eq: "7" }) {
        cloudinary: childCloudinaryAsset {
          fluid(transformations:["e_grayscale"] maxWidth: 1500) {
            ...CloudinaryAssetFluid
          }
        }
      }
    }`);

    const bannerImage = data.bannerImage.cloudinary.fluid;

    return (
        <Layout>
            <SEO title="Home"/>
            <Box mb={[10, 20, 100]}>
                <Heading size={'xl'} m={3} textAlign={"center"}>Responsive Banner Image</Heading>
                <Box>
                    <Image fluid={bannerImage}/>
                </Box>
            </Box>
            <Text my={5}>Click any of the buttons below to see the gallery or single Image with
                the <i>getFluidImageObject</i> API</Text>

            <Box>
                <Button variantColor={'teal'} mr={10} mb={[2, 0, 0]}>
                    <Link to="/gallery"> Gallery Images</Link>
                </Button>

                {/_Button to single page with getFluidImageAPI_/}
                <Button variantColor={'green'} mb={[2, 0, 0]}>
                    <Link to="/single">API Image</Link>
                </Button>
            </Box>
        </Layout>
    )
};

export default IndexPage

In the above code, Chakra UI styles the components for a responsive layout and responsive typography, with breakpoints for mobile, tablet, and desktop.

在上面的代码中,Chakra UI使用响应式布局和响应式排版为组件设置样式,并为移动设备,平板电脑和台式机提供断点。

Now restart the development server for the updated look of the webpage.

现在,重新启动开发服务器以获取网页的更新外观。

Notice the lazy-loaded image?

注意到延迟加载的图像了吗?

As a reference, here's the deployed app on Netlify. The complete code is in the GitHub repository.

作为参考,这是Netlify上已部署的应用程序 。 完整的代码在GitHub存储库中

摘要 ( Summary )

You now know how to fetch images with getFluidImageObject from Cloudinary into gatsby-image for GatsbyJS projects. getFixedImageObject fetches fixed images for gatsby-image in a similar manner.

您现在知道了如何使用getFluidImageObject从Cloudinary获取图像到GatsbyJS项目的gatsby-image中。 getFixedImageObject以类似的方式获取gatsby-image的固定图像。

Coming up is part 3, which describes how to add a dark mode as a toggle for the website and convert the site to a progressive web app (PWA) with only a few lines of code. Pretty amazing.

接下来是第3部分,它描述了如何添加暗模式作为网站的切换,以及如何仅用几行代码即可将网站转换为渐进式Web应用程序(PWA)。 相当了不起。

翻译自: https://scotch.io/tutorials/serving-remote-optimized-images-w-gatsby-image-wo-graphql

gatsby

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值