#Is it possible to use the `sharp` library directly in Astro components?

4 messages · Page 1 of 1 (latest)

drowsy quest
#

I'd like to be able to run crop and resize operations in my Astro files. The easiest way I can think to do this, instead of extending getImage , is to import sharp directly into my components and do the processing there.

Something like this. Very much pseudo-code.

import sharp from "sharp";

// Get an ImageMetadata object
import hero from "src/images/stock-gaming-landscape.jpg";

// Process it directly with sharp and export it as...something. File, buffer, etc.
const result = await sharp(hero.src)
  .resize(2500, 1667)
  .toFile("src/images/stock-gaming-landscape-modified.jpg");

---

<!-- Consume the result in an Image or img -->
<Image src={result} />
neon terrace
#

Following because I'm curious too!

fallen solstice
#

There might be better solutions, and what I'm proposing might not work due to some internal limitations that I'm not aware of. But you could try to use import.meta.glob to import the image you write to disk. Again, haven't tested this, but it's possible it works. You would however run the image through sharp twice, if you use astro's image component. If you want to skip the second optimisation you could pass image.src to a plain img element.
Also, I'm pretty sure you can't pass an imported image to sharp, you would have to read it to a buffer yourself

---
import sharp from "sharp";
import fs from 'node:fs/promises';

const hero = await fs.readFile("src/images/stock-gaming-landscape.jpg");

await sharp(hero)
  .resize(2500, 1667)
  .toFile("src/images/stock-gaming-landscape-modified.jpg");

const image = import.meta.glob<{ default: ImageMetadata }>("src/images/stock-gaming-landscape-modified.jpg");
---

<Image src={image} />
drowsy quest
#

Oh that's a good direction to go in, I'll look into that!