Is there any way to specify the process that should run after file being uploaded?
For instance I want to force jpg/png to webp format for all uploaded images with "sharp" lib, either before or during image sizes generation.
Hey @chladog — good question!
What I'd do is probably leave the existing jpg / png in place, but add some new fields for your webp
URLs to your upload-enabled collection. This way you still have the originals and can use them if your users' browsers are not webp-compatible.
Here's how I'd do it:
afterChange
collection hookfile
from the req
, and the req.payloadUploadSizes
, and then convert both the main file and each of your resized versions to webp
webp
versions to disk or whereverThis could be a great plugin actually. I bet other people would have use for this as well.
Does this help? I'd be happy to continue to shine some light here for you!
Thank you for great suggestions. Based on them I made a new plugin:
npm payload-webp
github here
I hope it can be useful to anyone!
I also extended your concept with afterDelete hook to delete webp files on media delete as well.
I found out that some methods from payload src would be useful, though are not part of the package so I had to make similar ones. Especially https://github.com/payloadcms/payload/blob/master/src/uploads/getBaseFields.ts would be useful. I also had to deep import these types: FileData, IncomingUploadType, AfterChangeHook, AfterDeleteHook - maybe make them accessible from payload/types? :-)
@chladog This is awesome! We can look into exporting those upload field types. For the hook types, those are exported with a "Collection" prefix, so in this case you'd use CollectionAfterChangeHook
and CollectionAfterDeleteHook
.
While working on this another topic arised regarding image sizes config which currently allows to set just dimensions and crop position. However it would make more sense to be able to pass full sharp.resize options.
Currently only hard crop is possible however I need to generate sizes with fit/contain property as my use case is that I want different image resolutions keeping their aspect ratios to be able to load correct image size per device with srcset.
Additionally should be possible to provide only width or height, not mandatorily both, as that would be valid as well.
You need to provide two dimmensions, but one of them might be NULL, and in that case it is not processed.
Hey @chladog — yes, as @quornik is saying, you can currently pass null
as a width or height which will allow images to keep their aspect ratio(s).
But, we could also pretty easily add support for all other Sharp options, too. I have opened up a new Feature Request for that. Would be pretty easy.
Star
Discord
online
Get dedicated engineering support directly from the Payload team.