How to replace image attachment, keeping other data

I am playing with an app (an admin tool) to do some image optimisation. As there is no possibility yet to intercept and optimise user uploaded images, the second best option is to enable admins to do some image crushing on occasion. 30 MB heavy 40 megapixel images uploaded for web use is unfortunate for image creation performance as well as backup size.

Using content studio, I am able to edit an image, and replace just the image attachment, keeping some of the metadata, and most importantly keeping the same _id for the image.

However, I lose crop and focal info, as all image info understandably is rebuilt. The user may well have uploaded an entirely different image.

In my tool I want to automate this. I’ll have user thresholds for which input images to select for crushing, and more user settings for output quality and size.

I then want to do a similar image replacement, keeping the _id, but I will replace the selected images by automatically generating smaller version of itself, thus keeping aspect ratio, enabling me to also keep existing focal point, crop and zoom info. (Thank you Enonic for using relative values here!). Actually I could keep all info besides the new physical dimensions in byte and pixel size.

Am I able to do this is javascript and Enonic libs alone? Do I need to go all nodelib repo ninja and sort of hack this together? Or is it simply not doable in js? Can I use

The steps I feel I need (in my mind):

  • Remember old data.media values (focal, crop, zoom)
  • Use contentLib.getAttachmentStream to get imagestream from the existing image
  • Somehow scale that stream
  • Then overwrite the old image with this new stream
  • Somehow get (and set) new values for sizes (perhaps by using .createMedia?)
  • Restore the old data.media values

I was thinking of using contentLib.getAttachmentStream to get the existing image, resize it by some black magic, and perhaps use contentLib.createMedia to get the new data. But how do I replace the existing attachment of the existing image only, keeping the old _id?

If this made sense to anyone, I’d be very grateful for any pointers!

I think you need to go down to the node layer to achieve what you want.
I’m also sceptical to what happens if you change some image and then run toolbox reprocess.
http://xp.readthedocs.io/en/stable/reference/toolbox/reprocess.html

2 Likes