In my nodejs application I need to extract a rectangular part of a JPEG image. I have the coordinates (x, y, width, height), I just need to crop.
There are many libraries that can do this (sharp, jimp, lwip, etc) but they all follow the decompress-modify-recompress pattern.
Since this is a server application and I'll probably need to do this for multiple pictures per second, I'd like to make it as performant as possible.
Luckily, I don't need the crop to be precise. It's no problem if the result is a few pixels larger. Thus I could use lossless JPEG extraction1 on properly aligned coordinates. It would both save CPU cycles, memory and avoid any potential quality loss.
I know this can be done because there are already tools out there that do it - just none that I could find were written in Javascript. I would also like to avoid CLI tools because I suspect that the overhead of writing to disk/calling tool/collecting the result would be far greater than just doing the recompression dance in memory with the available libraries (however if you have an argument for this approach, I'll accept that as an answer as well).
So - how do I losslessly crop a JPEG image (on properly aligned coordinates), in Javascript (node.js, server side)? The output is, of course, another JPEG image.
1 Note that "lossless" in this case doesn't mean "lossless JPEG". It means "lossless crop", where a part of a JPEG is extracted without decompressing/recompressing it. It's one of the few lossless operations that are possible on a JPEG.