Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Image optimization

default discord avatar
julian.urabllast year
2

Hey folks,


just diving into payload 🙂 I was wondering if it was possible to use external APIs like TinyPNG for image optimization through hooks.


I've read sharp's image quality feature can be used to reduce file size, but I'm not sure how it compares to tinify.


Thanks a lot and cheer!

  • discord user avatar
    jmikrut
    last year

    Hey @julian.urabl — you're right, Sharp can optimize images as well. There's a

    quality

    option that can be used like this:



    export const Media: CollectionConfig = {
      slug: 'media',
      upload: {
        staticDir: path.resolve(__dirname, '../../media'),
        formatOptions: {
          format: 'jpg',
          options: {
            quality: 40,
          },
        },
      },
      fields: [],
    }


    you can control how much to compress the image



    among many other things



    otherwise, you could certainly ship off your images to

    TinyPNG

    if you wanted to via a

    beforeOperation

    hook



    the originally uploaded file is available on

    req.files.file


    and then you can take it, do what you want, and then replace it

  • default discord avatar
    julian.urabllast year

    Awesome thank you! I'll set out to do some testing and try and compare the two. If TinyPNG turns out to have some additional benefits, perhaps I can even contribute with a plugin. Thanks for the amazing work!



    Would it be possible to preserve the original file type while optimising images with formatOptions? Perhaps it would even be possible to treat jpg and png differently?



    For anyone interested: I did some testing and compared the results from Sharp with TinyPNG and couldn't see any differences in quality with jpg.

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.