Can ImageMagick be prevented from overwriting an existing image?
Asked Answered
C

2

6

When converting an image, ImageMagick's default behavior seems to be to overwrite any existing file. Is it possible to prevent this? I'm looking for something similar to Wget's --no-clobber download option. I've gone through ImageMagick's list of command-line options, and the closest option I could find was -update, but this can only detect if an input file is changed.

Here's an example of what I'd like to accomplish: On the first run, convert input.jpg output.png produces an output.png that does not already exist, and then on the second run, convert input.jpg output.png detects that output.png already exists and does not overwrite it.

Chimere answered 30/12, 2018 at 21:39 Comment(2)
It's like most programs from the Unix world - it kind of assumes you know what you are doing. It's more like a Windows approach to ask if you really meant what you typed. I guess it's just a different ethos.Bernabernadene
You can script a test if the file exists or not and then do your convert as desired. That is easy in Unix bash for example. See shellhacks.com/bash-test-if-file-existsHomogenetic
B
3

Just test if it exists first, assuming bash:

[ ! -f output.png ] && convert input.png output.png

Or slightly less intuitively, but shorter:

[ -f output.png ] || convert input.png output.png

Read it like this... ”either it exists, or (if not), create it”

Bernabernadene answered 9/8, 2021 at 9:44 Comment(0)
V
0

Does something like this solve your problem?

It will write to output.png but if the file already exists a new file will be created with a random 5 character suffix (eg. output-CKYnY.png then output-hSYZC.png, etc.).

convert input.jpg -resize 50% $(if test -f output.png; then echo "output-$(head -c5 /dev/urandom | base64 | tr -dc 'A-Za-z0-9' | head -c5).png"; else echo "output.png"; fi)
Vetavetch answered 13/5, 2021 at 0:56 Comment(1)
To generate a random name you could use mktemp output-XXXXX.png instead of /dev/urandom. This is easier and also checks that the random name is unused.Boldfaced

© 2022 - 2024 — McMap. All rights reserved.