简体   繁体   中英

mozcjpeg - optimize original image

I'm trying to optimize sample.jpg with mozcjpeg, but I want it to compress sample.jpg, and not creating another file.

I run this command:

mozcjpeg -quality 80 sample.jpg > sample.jpg

and I get

Empty input file

What's the right way to do it?

PS I have a bash script that runs once a day to optimize images created in the last 24 hours.

只需使用不同的输出文件名,否则它会立即被覆盖。

You're reading the file and overwriting it at the same time. Instead, make an intermediary file:

tmp_file="$(mktemp)"
mozcjpeg -quality 80 sample.jpg > "${tmp_file}"
mv "${tmp_file}" sample.jpg

anycmd foo.jpg > foo.jpg is understood as:

  • The shell will open foo.jpg for write (overwriting any existing data).
  • The shell will fork and set this open file as the stdout.
  • The shell will exec anycmd foo.jpg .

So, by the time the command is executed, the original file is already gone. How can you work around that?

Well, you can create a temporary file, as suggested in the other answer .

Alternatively, you can use sponge . It's part of moreutils package.

$ whatis sponge
sponge (1)           - soak up standard input and write to a file

This tool allows you to write:

mozcjpeg -quality 80 sample.jpg | sponge sample.jpg

It works because sponge will first read all of the stdin (in memory), and only after stdin reaches EOF it will open the file for writing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM