#With responsive flag on, getImage generates more crops than needed

4 messages · Page 1 of 1 (latest)

chilly sonnet
#
import { shouldBuildImages } from "@src/utils/envUtils";
import { getImage } from "astro:assets";

const buildImages = shouldBuildImages();

export const OG_IMAGE_SIZE = {
  width: 1200,
  height: 630,
};

export default async function getOptimizedOgImage(
  imagePath: string,
  allImages: Record<
    string,
    () => Promise<{
      default: ImageMetadata;
    }>
  >,
) {
  const isExternalImage =
    imagePath.startsWith("https://") || imagePath.startsWith("http://");

  if (!isExternalImage && !allImages[imagePath]) {
    throw new Error(`OG image ${imagePath} not found`);
  }

  if (!buildImages) {
    return null;
  }

  return await getImage({
    src: isExternalImage ? imagePath : allImages[imagePath](),
    format: "png",
    quality: 90,
    ...OG_IMAGE_SIZE,
  });
}

With experimental: { responsiveImages: true, },

This function generates more than one image, but I only need one. Is there a way to override this?

potent knotBOT
#

Hi @chilly sonnet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can control the number of image crops generated by the getImage() function when the experimental.responsiveImages flag is enabled.

By default, enabling responsive images causes Astro to generate multiple image sizes (crops) for responsive behavior. However, you can override this behavior for a specific image by setting the layout property to "none" in your getImage() options. When layout: "none" is set, responsive behavior is disabled for that image, and only a single image will be generated at the specified size:

return await getImage({
  src: isExternalImage ? imagePath : await allImages[imagePath](),
  format: "png",
  quality: 90,
  ...OG_IMAGE_SIZE,
  layout: "none", // disables responsive crops
});

This is documented in the responsive image properties section:

layout: ... If set to none, responsive behavior is disabled for this image and all other options are ignored. Defaults to none, or the value of image.experimentalLayout if set.
Responsive image properties

So, to generate only a single image with getImage(), set layout: "none" in your options.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@chilly sonnet Kapa.ai is still learning and improving, please let me know how I did by reacting below.