#markdown images

4 messages · Page 1 of 1 (latest)

stray meadow
#

How can I control the size of images in markdown files in content collections?

safe cedarBOT
#

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

#

In Astro, you can control the size of images in markdown files in content collections by using the image helper for the content collections schema. This allows you to validate the image metadata using Zod.

Here is an example of how you can do this:

import { defineCollection, z } from "astro:content";

const blogCollection = defineCollection({
  schema: ({ image }) => z.object({
    title: z.string(),
    cover: image().refine((img) => img.width >= 1080, {
      message: "Cover image must be at least 1080 pixels wide!",
    }),
    coverAlt: z.string(),
  }),
});

export const collections = {
  blog: blogCollection,
};

In this example, the cover image must be at least 1080 pixels wide. If you want to control the height, you can add a similar refinement for the height.

After defining the schema, you can use the image in your Astro component like this:

---
import { Image } from "astro:assets";
import { getCollection } from "astro:content";

const allBlogPosts = await getCollection("blog");
---
{  
  allBlogPosts.map((post) => (
    <div>
      <Image src={post.data.cover} alt={post.data.coverAlt} />
      <h2>
        <a href={"/blog/" + post.slug}>{post.data.title}</a>
      </h2>
    </div>
  ))
}

In this example, the Image component from Astro is used to display the image. The src and alt attributes are passed to the Image component.

Please note that the Image component from Astro optimizes your images for better performance. However, it does not provide a way to control the size of the image directly in the markdown file. If you need more control over your image attributes, you might want to consider using the .mdx file format, which allows you to include Astro’s Image component or a JSX img tag in addition to the Markdown syntax.