Revert compressed file if larger
Oxipng and jpegoptim already skip over files that'll be larger by default. pngquant has an option to skip them if larger, which I added. cwebp doesn't have any option for this as far as I know, so the file has to be reverted manually. I'm not sure if there's a cleaner way to do it. The attached image shows the result of a file being skipped/reverted.
I'm also not sure if scour has an option to skip files if they'll end up being larger, but if #227 gets fixed, that won't be a problem. The check I added should catch compressed SVG files that end up being larger anyway.
~~This currently doesn't properly handle reverting files while in overwrite mode. I'll implement that when I have the time.~~ (Done).
Closes #172
This should work in overwrite mode. I wish the solution was cleaner, but this was the best I could come up with. I should note something that I found on the Python docs, however:
Warning: Even the higher-level file copying functions (shutil.copy(), shutil.copy2()) cannot copy all file metadata.
On POSIX platforms, this means that file owner and group are lost as well as ACLs. On Mac OS, the resource fork and other metadata are not used. This means that resources will be lost and file type and creator codes will not be correct. On Windows, file owners, ACLs and alternate data streams are not copied.
This does make me a little hesitant to use shutil.copy2(), but this was the best solution I could think of. It's also only really bad if safe mode is off, since the file is overwritten. And, it seems like as much metadata as possible is preserved. Ultimately up to you, though.
Is there anything I could/should do to improve this? I'm still not super enthusiastic about the solution in overwrite mode, but ideally there would just be an option upstream for the WebP and SVG(?) compressors to skip files if larger anyway.
I will try to review the PR in the next few days, I put it on my TODO :)
Alright, thank you :+1:
To summarize:
- jpegoptim seems to already skip larger files (because it has an --force option)
- pngquant has
--skip-if-largerthat you added - oxinpng already skip larger files (because it has an --force option)
So shutil.copy2() will be useful for libwebp and scour. But for SVGs I doubt that they can be larger.
So only really useful for libwebp. Could you add a condition to only apply this feature to webp images?
Sorry for the long review...
Could you add a condition to only apply this feature to webp images?
I can, but this should only run if the output file is larger. It won't run for SVGs if SVGs aren't going to be larger. Up to you though.
And don't worry about the long review, it's fine :)
Thanks for you work! Could be improved in the future to have an indicator in the UI to inform when this mechanism has been applied on an image.