I need to optimize some images, but not change their name.
jpegtran -copy none -optimize image.jpg > image.jpg
However, this seems to crea
jpegtran -copy none -progressive -optimize -outfile filename filename
For comprehensive optimization: -copy none tells jpegtran to suppress all comments and other excess baggage present in the source jpeg, progressive generates a progressive jpeg, -optimize performs the actual optimizations, and -outfile sets the output file name. The last parameter is the input file name: if they are the same, your file is optimized in place.
Edit: you might want to also try mozjpeg, according to this article on lossless jpeg compression tools http://blarg.co.uk/blog/comparison-of-jpeg-lossless-compression-tools
how about:
jpegtran -copy none -optimize -outfile image.jpg image.jpg
I'm not a shell expert by any means, but I think that with your original command, as soon as it is executed, the redirect is set up which overwrites your image.jpg. Then when jpegtran tries to read it in it finds an empty file.
I did it in three lines:
jpegtran -optimize image.jpg > image.jpg-opt
cp image.jpg-opt image.jpg
rm image.jpg-opt
Works well.
[edit:] This works only for one file at a time.
Without sponge, another alternative with lower HDD or SSD writing access is to use the /dev/shm to save the temporary file and then overwrite it locally right away.
jpegtran -copy none -optimize image.jpg > /dev/shm/tmp.jpg && cat /dev/shm/tmp.jpg > ./image.jpg
The concept can be easily adapted into any script, perhaps with caveats about the temporary filename not being the same, in order to avoid collisions if there are multiple instances running at the same time. It's possibly interesting to think about some unique filename pattern generation scheme, perhaps something along the lines of ${originalfilename}-jpgtrantmp-$$
.
I use this script. Works flawlessly. I hope this helps.
https://gist.github.com/iimos/7424025
#! /bin/sh
EXTENSIONS="jpe?g"
if [ -z "$1" ]; then
DIR="`pwd`"
else
DIR="$1"
fi
# Optimize JPEG images
find "$DIR" -regextype posix-egrep -regex ".*\.($EXTENSIONS)\$" -type f | xargs -I{} jpegtran -optimize -progressive -outfile "{}.optimized" "{}"
# Rename xxx.jpg.optimized -> xxx.jpg
find "$DIR" -name '*.optimized' -print0 | while read -d $'\0' file; do
chown $(stat -c "%U:%G" "${file%.optimized}") "$file"
chmod $(stat -c "%a" "${file%.optimized}") "$file"
mv -f "$file" "${file%.optimized}";
done
Usage 1:
optimize-images.sh /images/dir
Usage 2:
cd /images/dir
optimize-images.sh
Another option if -outfile
is not supported:
jpegtran -copy none -optimize image.jpg | sponge image.jpg
sponge
is part of moreutils.