简体   繁体   English

mozcjpeg - 优化原始图像

[英]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.我正在尝试使用 mozcjpeg 优化 sample.jpg,但我希望它压缩 sample.jpg,而不是创建另一个文件。

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. PS 我有一个每天运行一次的 bash 脚本来优化过去 24 小时内创建的图像。

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

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: anycmd foo.jpg > foo.jpg理解为:

  • The shell will open foo.jpg for write (overwriting any existing data). shell 将打开foo.jpg进行写入(覆盖任何现有数据)。
  • The shell will fork and set this open file as the stdout. shell 将 fork 并将这个打开的文件设置为 stdout。
  • The shell will exec anycmd foo.jpg . shell 将执行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 .或者,您可以使用sponge It's part of moreutils package.它是moreutils包的一部分。

$ 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.它起作用是因为sponge将首先读取所有标准输入(在内存中),并且只有在标准输入到达 EOF 后才会打开文件进行写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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