How to use ImageMagick command line on Windows?
My goal is to determine the compression parameters of the jpeg image that I have. As I understood from this answer, it’s possible using the ImageMagick function identity. I downloaded from the official site and installed ImageMagick-7.0.2-7-Q16-x64-dll.exe. Now, I have an application with GUI called ImageMagick Display that seems useless. Where can I find an IM command line to type this:
5 Answers 5
Since it is version 7.x, there is a checkbox at the time of installation that says something like ‘install legacy (or older) utilities’. I am not sure what the exact text is, but you need to select that checkbox during installation.
Once done, you will be able to use the commands from command line.
Another option is to use the command magick identify —version
For version 6.x, it is not necessary.
Open cmd>give access to your path in cmd then hit Enter.
Now type magick identify «D:\your path\name of file» then hit Enter,
Type it into the command prompt; alternatively you could put it into a batch file and drop your image over the batch file icon. But in both cases you would then need to think of a way to display the result.
Try this from command line
type «C:\Program Files\ImageMagick-7.0.7-Q16\magick.exe» identify -format ‘%Q’ yourimage.jpg
replace «C:\Program Files\ImageMagick-7.0.7-Q16\magick.exe» with your directory that has ImageMagick-. \magick.exe installed, and place double quotes at the start of «C:\. and at the end . magick.exe» ,
Hope ImageMagick is installed in location C:\Program Files (x86)\ImageMagick-7.0.8-Q16
If you are using Imagemagick version above 7.0
Пакетная обработка изображений в Windows с ImageMagick. Часть I
Вначале была установка
Есть версии много ImageMagick. Если машина уже не молода и памяти не больше 1024 Мбайт — вам уготована Q8. Иначе, загружайте Q16.
Во время установки, отметьте чекбоксы:
Таким образом, мы получим весь комплект утилит и добавим их в системную переменную path.
Пакетное сжатие и ресайз PNG и JPG с помощью ImageMagick
Ресайз и сжатие выполняют две утилиты ImageMagick:
mogrify.exe — изменяет исходное изображение.
convert.exe – на основе исходного, создает новое, измененное изображение.
JPG. Основные опции ImageMagick для сжатия и ресайза
Важно понимать, что нет «лучших» настроек. Применение одинаковых настроек ко всем изображениям, не даст лучших результатов. Некоторые изображения будут выглядеть размытыми, или наоборот, слишком резкими. Поэтому нужно выбрать «средние» параметры, которые вам подойдут.
Примеры использования параметра -thumbnail:
Ресайз по ширине 100px, с сохранением соотношения сторон (высота изменится пропорционально):
Ресайз по высоте 150px, с сохранением соотношения сторон (ширина изменится пропорционально).
Ресайз без сохранения соотношения сторон:
Для удобной пакетной обработки изображений, воспользуемся батниками. Это пакетные файлы с расширением .BAT или.CMD. В примерах с jpg, установим сжатие с качеством 80 и ресайз по ширине 800px.
Батник будет изменять изображения, только в каталоге, из которого он запущен. Он создаст папку «Compressed» и запишет в нее измененные изображения, добавляя к имени «_Compressed.jpg».
JPG — батники для сжатия и ресайза с потерями
Что делает это батник? В каталоге, из которого он запущен, находит все файлы с расширением *.jpg. Здесь же, создает папку «Compressed» и копирует в нее все обработанные изображения, добавляя к их имени «_Compressed.jpg».
Приведу для примера, батник с утилитой mogrify.exe (обработает и перезапишет все изображения .jpg, в каталоге, из которого будет запущен):
PNG. Основные опции ImageMagick для сжатия и ресайза
PNG сжимается без потерь и сохраняет прозрачность ( альфа-канал).
Хотя, его тоже возможно сжимать с потерями. Также, как и с jpg, можно использовать опции:-gaussian-blur, -strip, -resize, -thumbnail, -unsharp.
А также множество вариантов с опциями для png:
-define png:compression-filter=2
-define png:compression-level=9
-define png:compression-strategy=1
-colors 255 — Почему не 256? Потому что 1 резервируется для альфа-канала.
-depth 8 — количество бит.
-quality 90 — для png этот параметр имеет иной принцип работы и другие значения, чем для jpg.
Подробнее об этих опциях, смотрите на сайте ImageMagick. Их очень много, на любой вкус и цвет. Я привел средние параметры, которые меня устроили. Теперь давайте посмотрим, как их можно использовать в батниках.
PNG — батники для сжатия и ресайза
Изменяя опции и значения параметров в этих батниках, можно подобрать подходящий для вас вариант, для пакетного сжатия и ресайза.
Что делать, если вы изменили батник, и он перестал работать?
- Убрать все пробелы в конце строк.
В Notepad++ это можно сделать так: выделить все, Правка — Операции с Пробелами — Убрать замыкающие пробелы и сохранить. Или: Ctrl+A — Ctrl+Shift+B — Ctrl+S. - Проверьте, стоит ли кодировка UTF-8 без BOM. Если же вы используете в батнике кириллицу, кодировка OEM 866.
- Убедитесь, что используются подходящие параметры для данного формата.
Загрузить все батники >>
И на десерт
Я протестировал все популярные PNG компрессоры. Для себя сделал вывод: лучшее сжатие PNG с потерями дает pngquant. Если применять его для сжатия скриншотов. С другими изображениями — не тестировал. Работает очень быстро. С параметром «—strip» — удаляет все метаданные.
pngquant — это PNG-компрессор, который значительно уменьшает размеры файлов путем преобразования изображений в более эффективный 8-битный PNG-формат с альфа-каналом (часто на 60-80% меньше, чем 24/32-битные PNG-файлы). Сжатые изображения полностью совместимы со стандартами и поддерживаются всеми веб-браузерами и операционными системами.
Параметры командной строки pngquant.
И конечно же есть автомат Калашникова батник для пакетной обработки:
Чтобы все работало, нужно положить pngquant.exe рядом с батником. Либо скопировать его в любую папку и в батнике, вместо «pngquant.exe», указать путь «YourPath\pngquant.exe»
Примечание: pngquant почему-то не обрабатывает файлы с кириллическими именами.
Но, мы отвлеклись. Во второй части продолжим и поговорим о пакетном добавлении водяных знаков с помощью ImageMagick.
Windows command line ImageMagick percent escapes
I’m trying to use ImageMagick from the command line in Windows 7 to convert many images at once. I would like to use the -set option interface, but I’m getting unexpected results. A short example of some of the weirdness I’m seeing is this:
Notice that the underscore character is mysteriously deleted from the output filename. I can use a caret (^) to escape the second percent sign in order to retain the underscore:
What’s going on here? Why does inserting the caret cause the underscore to be retained? Is the caret (^) even the correct escaper to be trying? Is this behavior due to command shell environment variable expansion or does the weirdness result from the way ImageMagick handles the percent escapes? Either way, are there general principles regarding use of percent symbols in command line args that can be followed to cause predictable behavior?
What I actually want to do is a version of the above command with many more properties set, that can handle very filenames with special characters like spaces and percent symbols, but it seems foolish to try that if I can’t understand this much simpler example. Ultimately, I’ll need to execute the command from a .NET program.
Adding some more examples to answer questions in comments from @dbenham and @Synetech.
Moving the underscore from before the second percent symbol, as in the latter example above, to before the underscore, produces a file named hello^world.png :
Caret-escaping the surrounding quotation marks always always results in helloworld.png , regardless of where carets are placed within:
1 Answer 1
I can’t quite explain the weird behavior you are seeing. It almost seems like it is a result of cmd.exe percent processing, but it does not quite match the cmd.exe behavior as I understand it.
Escaping percents within a batch file is easy — just double them up. But that does not work from the command line. Technically, there is no way to escape a percent on the Windows cmd.exe command line.
The command line can expand percents in one of two ways:
1) Expand Environment variables.
If text between two percents matches the name of an environment variable, then the percent construct is replaced by the value.
If the text between the percents does not match an environment variable name, then the full original text is retained.
Microsoft’s own documentation claims you can escape the percent by putting a caret in front.
But that is not really escaping the percent. Instead, it is looking for a variable named test^ , and not finding it. So the original text is undisturbed. Then the carets are removed during the normal escape processing. This can be proven by defining a variable with the caret in the name.
The caret before the first percent does nothing. You can place a caret anywhere between the percents and it will prevent expansion of the variable as long as no variable exists with the caret in the name.
If the text is quoted, then the caret will not be dropped unless the quotes are also escaped.
The situation is a bit more complicated when there are colons. The colon is used by variable expansion for substitution and substring operations. The variable name is the text between the first percent and the colon.
If the text between the first percent and the colon does not match a variable name, or if the text between the colon and the last percent is not a valid substitution or substring construct, then the original text is preserved without substitution.
This last example most resembles your situation. The text between your first percent and the colon does not match a variable, and the text between the colon and the last percent is not a substitution or substring construct, so the entire construct should be preserved, including the underscore. For this reason, I don’t see how cmd.exe could be stripping your underscore. But the fact that adding a caret before the second percent preserves the underscore has me suspicious. I’d really like to know what happens if you move the caret before the underscore instead.
2) Expand FOR variables
Not an issue in your case, but percents can also cause issues if a FOR loop is in effect. There is no way to protect the percent by using a caret in this case, because the caret is stripped prior to the FOR variable expansion. In this example, I want the output to read %A=1 , but it does not work.
The most convenient way to protect the percent is to introduce another FOR variable
It works just as well to put the A in another variable
Update
One good way to test where the underscore is getting stripped is to put ECHO before your command. If the original command is preserved with the underscore, then you know that the convert utility must be the culprit.
The underscore is preserved on my machine 🙂