Linux imagemagick save jpeg

ImageMagick или как сжимать изображения в ОС Linux

Категории блога

Очень долгое время я пользовался программой RIOT, но на тот период я плотно сидел на операционных системах семейства Windows. И вот на протяжении уже нескольких лет я использую ОС Ubuntu. Долгое время я работал с RIOT установленным через wine. С сегодняшнего дня я решил использовать меньше костылей и заняться вплотную изучением команд терминала Linux. На сайте программы RIOT есть ссылка на скачивание плагина для популярного редактора Gimp. Но запускать софт такого размера ради сжатия одного изображения мне крайне не хочется.

Поэтому сегодня речь пойдет об утилите ImageMagick.

ImageMagick это огромный бесплатный многоплатформенный комплекс утилит, который поддерживается многими языками программирования, и существует как отдельный комплекс. Думаю тем, кто как-то связан с веб-разработкой, с ImageMagick знаком не понаслышке.
Конечно может, кому то покажется совершенно неудобным работать с изображениям с помощью консольной утилиты. Но я в любом случае советую попробовать.

Установка ImageMagick

На данный момент моей операционной системой является Linux Ubuntu 14.04, поэтому и примеры буду приводить именно из нее. Итак перейдем к установке ImageMagick в Linux Ubuntu 14.04:
Перед тем как устанавливать этот пакет, проверьте, возможно он у вас уже есть, и какая у него версия:

dpkg -s imagemagick

Это команда проверит какая версия пакета ImageMagick установлена в вашей системе.
У меня этот пакет оказался установленным. Для тех у кого этого пакета нет, выполните следующую команду(собственно сама установка):

sudo apt-get install imagemagick

Команды для работы ImageMagick в терминале

Команд и утилит входящих в состав ImageMagick очень много, и описывать все я здесь не буду, так как не вижу в этом особого смысла. Ведь все есть в официальной документации, которая лежит здесь. Я покажу лишь те которые использую сам.

convert — изменение размера изображения

input_image — имя файла изображения, которое нужно взять за основу для работы
commands — дополнительные команды/параметры
out_image — имя изображения в которое будут сохранены все преобразования исходного

Что бы просто конвертировать изображение одного формата в другой формат, нужно сделать следующее:

convert img.png img.jpg

-quality

Уровень сжатия изображения можно указать с помощью параметра -quality:

convert img.jpg -quality 75 img1.jpg

Вы можете указать здесь в качестве значения цифры от 1 до 100. По умолчанию используется значение 92. Я обычно для блога сжимаю с параметром 75.

-resize

Для того что бы изменить размер изображения нужно воспользоваться параметром -resize:

convert img.jpg -resize 100×150 img1.jpg

Здесь есть несколько схем подобного сжатия:
-resize — изменение изображения и его размеров в пикселях, с сохранением соотношения сторон

convert img.jpg -resize 100×150 img1.jpg

Сжатие изображения по ширине до 100px, при этом высота будет сжата пропорционально

convert img.jpg -resize 100 img1.jpg

Аналогичное предыдущему, только здесь изображение сжимается по высоте до 150px

convert img.jpg -resize ×150 img1.jpg

-resize — изменение размеров изображения без сохранения соотношения сторон

convert img.jpg -resize 100×150! img1.jpg

-resize — изменение размера изображения в %(процентах)

convert img.jpg -resize 20% img1.jpg

-rotate

Для того что бы повернуть изображение существует параметр -rotate, где значение указывается в градусах:

convert img.jpg -rotate 20 img1.jpg

Группировка команд

Самое удобное что есть — это группировка команд. То есть по сути можно сделать следующее(изменить размер, повернуть на 120 градусов, и изменить качество, еще и поменять формат с png на jpg):

convert img.png -resize 100×400 -rotate 120 -quality 75 img.jpg

identify — проверка информации о изображении

Сокращенная информация о изображении:

А та же команда с параметром -verbose выведет полную информацию о изображении.

identify -verbose img.jpg

Пакетная обработка изображений с помощью ImageMagick

Я сам ей практически и не пользуюсь. Мне чаще все таки нужно работать с отдельными изображениями. Следующая команда обработает все изображения с разрешением .png повернет их на 180 градусов и запишет в файлы с новым именем rotated-предыдущее имя файла.

for file in *.png; do convert $file -rotate 180 rotated-$file; done

В общем утилита ImageMagick очень удобна и хороша в работе. А главное она сжимает практически без потерь качества, что немаловажно. Конечно она не подойдет для тех кто терпеть не может консоль. Но я для других — очень даже ничего:)
Пользуйтесь!;)

Источник

ImageMagick pdf конвертация в jpg

Нужно сконвертировать PDF документ в картинки, поскольку нужно активно увеличивать и прокручивать без тормозов.
Выбор пал на ImageMagick, как уже привычный и используемый пакет. Прошу помощи в решении фичи или баги с ним.

Конвертируем сразу из www, либо локально:
convert http://www.shema.ru/shema.ru/0_s/m_center/sharp/wf_939.pdf cxema.jpg

На выходе получаю две картинки по количеству страниц, но в ужасном пиксельарте, будто там разрешение 100х100. -quality 100 не помогает.

P.S. Вот за что люблю консоль, так это за @блю мозга. Сперва приходится решать сопутствующую проблему, что ничего не работает и править конфиг, потом убив на это время, запускаешь радостный, а всё равно работает через жопу. Просто из коробки отработать нормально нет, не слышали! 2020 скоро на дворе, а вот и ныне там.

Читайте также:  Полезные приложения для windows 10 ноутбук

Проблема в том, что вместо чтения документации, ты ноешь.

N можешь взять за 300, Y за 100.

Да, на всякий случай, зная что ты не будешь читать документацию и разбираться — порядок опций имеет значение.

Спасибо за решение. Про порядок ключей я знаю.
Вы путаете нытьё со сложностью поиска решения, засунутого на окраины Залупогорска.

Если бы я не искал решения, а просто жаловался какое говно эта ваша заливная рыба, то да, это было бы нытьё, а так я не ванга, не холмс, и не пожиратель макулатуры документаций мегабайтами.

Почему по дефолту не задан density, приемлемый для разборчивого прочтения? Почему он не выдаёт подсказку, какие ключи можно в этой инструкции использовать? Почему на каждый чих я должен по манам и Зажопинскам интернета отыскивать решение? Откуда мне знать какой ключ тут вообще нужен, даже пролистав https://imagemagick.org/script/command-line-options.php ? Может вам на ура ищется, а у меня не получилось. Будь утилита и маны более дружелюбными к пользователю, этой темы бы не было. Да, можете со снобизмом ответить мне в прежнем духе, ваше право на ваше мнение, как и моё на моё.

Даже если ты плохо ориентируешься в документации, поиск то всегда есть. Первая ссылка — https://www.imagemagick.org/discourse-server/viewtopic.php?t=12235 . Ответ во втором посте.

P.S. Никакого снобизма. Настроение плохое.

Кстати, я в ответе тоже накосячил. -quality ко входным файлам не применяется. Нужно без него. Из мана:

Only a limited number of setting are input-option. They include: -antialias, -caption, -density, -define, -encoding, -font, -pointsize, -size, and -texture as well as any of the miscellaneous options.

Спасибо. По поиску я нашёл массу описаний конвертации, и все они без упоминания доп. ключей, странно, что гуголь ни разу не предложил форум imagemagick.org.

Не понимаю. Без -quality проблема, с ним выходной файл ок. Причём тут входной файл? Пост вызвал взаимоисключающий параграф и деление на 0. =)

Альтернатива? Что-то не сработало. несмотря на -all Плодит кучу .params и .ccitt не понимаю, что это за формат, сделал в png:
pdfimages -png aaa.pdf aaa

Почему он не выдаёт подсказку, какие ключи можно в этой инструкции использовать? Почему на каждый чих я должен по манам и Зажопинскам интернета отыскивать решение?

Потому что это вам не Эппл, где всё решили за вас, и density поменять никак нельзя а Линукс, где подобное поведение — норма, и в самоистязании главный кайф.

кучу .params и .ccitt не понимаю, что это за формат

Про .ccitt — CCITT GROP FAX 3/4 (скорее 4), пользуется в tiff . Про .params — не вкурсах.

Источник

Convert Between Image Formats

Use the magick program to convert between image formats as well as resize an image, blur, crop, despeckle, dither, draw on, flip, join, re-sample, and much more. See Command Line Processing for advice on how to structure your magick command or see below for example usages of the command.

We list a few examples of the magick command here to illustrate its usefulness and ease of use. To get started, lets convert an image in the JPEG format to PNG:

Next, we reduce the image size before it is written to the PNG format:

    »/>

You can combine multiple image-processing operations to produce complex results:

or here we resize an image with improved quality:

You can find additional examples of using magick in Examples of ImageMagick Usage.

Option Summary

The magick command recognizes these options. Click on an option to get more details about how that option works.

-adaptive-blur geometry adaptively blur pixels; decrease effect near edges
-adaptive-resize geometry adaptively resize image with data dependent triangulation.
-adaptive-sharpen geometry adaptively sharpen pixels; increase effect near edges
-adjoin join images into a single multi-image file
-affine matrix affine transform matrix
-alpha on, activate, off, deactivate, set, opaque, copy», transparent, extract, background, or shape the alpha channel
-annotate geometry text annotate the image with text
-antialias remove pixel-aliasing
-append append an image sequence
-authenticate value decipher image with this password
-auto-gamma automagically adjust gamma level of image
-auto-level automagically adjust color levels of image
-auto-orient automagically orient image
-auto-threshold method automatically perform image thresholding
-background color background color
-bench iterations measure performance
-bias value add bias when convolving an image
-bilateral-blur geometry non-linear, edge-preserving, and noise-reducing smoothing filter
-black-threshold value force all pixels below the threshold into black
-blue-primary point chromaticity blue primary point
-blue-shift factor simulate a scene at nighttime in the moonlight
-blur geometry reduce image noise and reduce detail levels
-border geometry surround image with a border of color
-bordercolor color border color
-brightness-contrast geometry improve brightness / contrast of the image
-canny geometry use a multi-stage algorithm to detect a wide range of edges in the image
-caption string assign a caption to an image
-cdl filename color correct with a color decision list
-channel type apply option to select image channels
-charcoal radius simulate a charcoal drawing
-chop geometry remove pixels from the image interior
-clahe geometry contrast limited adaptive histogram equalization
-clamp set each pixel whose value is below zero to zero and any the pixel whose value is above the quantum range to the quantum range (e.g. 65535) otherwise the pixel value remains unchanged.
-clip clip along the first path from the 8BIM profile
-clip-mask filename associate clip mask with the image
-clip-path id clip along a named path from the 8BIM profile
-clone index clone an image
-clut apply a color lookup table to the image
-connected-components connectivity connected-components uniquely labeled, choose from 4 or 8 way connectivity
-contrast-stretch geometry improve the contrast in an image by `stretching’ the range of intensity value
-coalesce merge a sequence of images
-colorize value colorize the image with the fill color
-color-matrix matrix apply color correction to the image.
-colors value preferred number of colors in the image
-colorspace type set image colorspace
-color-threshold start-color — stop-color force all pixels in the color range to white otherwise black
-combine combine a sequence of images
-comment string annotate image with comment
-compare compare image
-complex operator perform complex mathematics on an image sequence
-compose operator set image composite operator
-composite composite image
-compress type image compression type
-contrast enhance or reduce the image contrast
-convolve coefficients apply a convolution kernel to the image
-copy geometry offset copy pixels from one area of an image to another
-crop geometry crop the image
-cycle amount cycle the image colormap
-decipher filename convert cipher pixels to plain
-debug events display copious debugging information
-define format:option define one or more image format options
-deconstruct break down an image sequence into constituent parts
-delay centiseconds display the next image after pausing
-delete index delete the image from the image sequence
-density geometry horizontal and vertical density of the image
-depth value image depth
-despeckle reduce the speckles within an image
-direction type render text right-to-left or left-to-right
-display server get image or font from this X server
-dispose method layer disposal method
-distribute-cache port launch a distributed pixel cache server
-distort type coefficients distort image
-dither method apply error diffusion to image
-draw string annotate the image with a graphic primitive
-duplicate count,indexes duplicate an image one or more times
-edge radius apply a filter to detect edges in the image
-emboss radius emboss an image
-encipher filename convert plain pixels to cipher pixels
-encoding type text encoding type
-endian type endianness (MSB or LSB) of the image
-enhance apply a digital filter to enhance a noisy image
-equalize perform histogram equalization to an image
-evaluate operator value evaluate an arithmetic, relational, or logical expression
-evaluate-sequence operator evaluate an arithmetic, relational, or logical expression for an image sequence
-extent geometry set the image size
-extract geometry extract area from image
-family name render text with this font family
-features distance analyze image features (e.g. contract, correlations, etc.).
-fft implements the discrete Fourier transform (DFT)
-fill color color to use when filling a graphic primitive
-filter type use this filter when resizing an image
-flatten flatten a sequence of images
-flip flip image in the vertical direction
-floodfill geometry color floodfill the image with color
-flop flop image in the horizontal direction
-font name render text with this font
-format string output formatted image characteristics
-frame geometry surround image with an ornamental border
-function name apply a function to the image
-fuzz distance colors within this distance are considered equal
-fx expression apply mathematical expression to an image channel(s)
-gamma value level of gamma correction
-gaussian-blur geometry reduce image noise and reduce detail levels
-geometry geometry preferred size or location of the image
-gravity type horizontal and vertical text placement
-grayscale method convert image to grayscale
-green-primary point chromaticity green primary point
-help print program options
-hough-lines geometry identify lines in the image
-identify identify the format and characteristics of the image
-ift implements the inverse discrete Fourier transform (DFT)
-illuminant type reference illuminant
-implode amount implode image pixels about the center
-insert index insert last image into the image sequence
-intensity method method to generate an intensity value from a pixel
-intent type type of rendering intent when managing the image color
-interlace type type of image interlacing scheme
-interline-spacing value the space between two text lines
-interpolate method pixel color interpolation method
-interword-spacing value the space between two words
-kerning value the space between two characters
-kmeans geometry K means color reduction
-kuwahara geometry edge preserving noise reduction filter
-label string assign a label to an image
-lat geometry local adaptive thresholding
-layers method optimize or compare image layers
-level value adjust the level of image contrast
-limit type value pixel cache resource limit
-linear-stretch geometry linear with saturation histogram stretch
-liquid-rescale geometry rescale image with seam-carving
-list type Color, Configure, Delegate, Format, Magic, Module, Resource, or Type
-log format format of debugging information
-loop iterations add Netscape loop extension to your GIF animation
-mattecolor color frame color
-median radius apply a median filter to the image
-mean-shift geometry delineate arbitrarily shaped clusters in the image
-metric type measure differences between images with this metric
-mode radius make each pixel the ‘predominant color’ of the neighborhood
-modulate value vary the brightness, saturation, and hue
-moments display image moments.
-monitor monitor progress
-monochrome transform image to black and white
-morph value morph an image sequence
-morphology method kernel apply a morphology method to the image
-motion-blur geometry simulate motion blur
-negate replace each pixel with its complementary color
-noise radius add or reduce noise in an image
-normalize transform image to span the full range of colors
-opaque color change this color to the fill color
-ordered-dither NxN ordered dither the image
-orient type image orientation
-page geometry size and location of an image canvas (setting)
-paint radius simulate an oil painting
-perceptible set each pixel whose value is less than | epsilon | to -epsilon or epsilon (whichever is closer) otherwise the pixel value remains unchanged.
-ping efficiently determine image attributes
-pointsize value font point size
-polaroid angle simulate a Polaroid picture
-poly terms build a polynomial from the image sequence and the corresponding terms (coefficients and degree pairs).
-posterize levels reduce the image to a limited number of color levels
-precision value set the maximum number of significant digits to be printed
-preview type image preview type
-print string interpret string and print to console
-process image-filter process the image with a custom image filter
-profile filename add, delete, or apply an image profile
-quality value JPEG/MIFF/PNG compression level
-quantize colorspace reduce image colors in this colorspace
-quiet suppress all warning messages
-radial-blur angle radial blur the image
-raise value lighten/darken image edges to create a 3-D effect
-random-threshold low, high random threshold the image
-range-threshold low-black, low-white, high-white, high-black perform either hard or soft thresholding within some range of values in an image
-read-mask filename associate a read mask with the image
-red-primary point chromaticity red primary point
-regard-warnings pay attention to warning messages.
-region geometry apply options to a portion of the image
-remap filename transform image colors to match this set of colors
-render render vector graphics
-repage geometry size and location of an image canvas
-resample geometry change the resolution of an image
-resize geometry resize the image
-respect-parentheses settings remain in effect until parenthesis boundary.
-roll geometry roll an image vertically or horizontally
-rotate degrees apply Paeth rotation to the image
-sample geometry scale image with pixel sampling
-sampling-factor geometry horizontal and vertical sampling factor
-scale geometry scale the image
-scene value image scene number
-seed value seed a new sequence of pseudo-random numbers
-segment values segment an image
-selective-blur geometry selectively blur pixels within a contrast threshold
-separate separate an image channel into a grayscale image
-sepia-tone threshold simulate a sepia-toned photo
-set attribute value set an image attribute
-shade degrees shade the image using a distant light source
-shadow geometry simulate an image shadow
-sharpen geometry sharpen the image
-shave geometry shave pixels from the image edges
-shear geometry slide one edge of the image along the X or Y axis
-sigmoidal-contrast geometry increase the contrast without saturating highlights or shadows
-smush offset smush an image sequence together
-size geometry width and height of image
-sketch geometry simulate a pencil sketch
-solarize threshold negate all pixels above the threshold level
-sort-pixels sorts pixels within each scanline in ascending order of intensity
-splice geometry splice the background color into the image
-spread radius displace image pixels by a random amount
-statistic type geometry replace each pixel with corresponding statistic from the neighborhood
-strip strip image of all profiles and comments
-stroke color graphic primitive stroke color
-strokewidth value graphic primitive stroke width
-stretch type render text with this font stretch
-style type render text with this font style
-swap indexes swap two images in the image sequence
-swirl degrees swirl image pixels about the center
-synchronize synchronize image to storage device
-taint mark the image as modified
-texture filename name of texture to tile onto the image background
-threshold value threshold the image
-thumbnail geometry create a thumbnail of the image
-tile filename tile image when filling a graphic primitive
-tile-offset geometry set the image tile offset
-tint value tint the image with the fill color
-transform affine transform image
-transparent color make this color transparent within the image
-transparent-color color transparent color
-transpose flip image in the vertical direction and rotate 90 degrees
-transverse flop image in the horizontal direction and rotate 270 degrees
-treedepth value color tree depth
-trim trim image edges
-type type image type
-undercolor color annotation bounding box color
-unique-colors discard all but one of any pixel color.
-units type the units of image resolution
-unsharp geometry sharpen the image
-verbose print detailed information about the image
-version print version information
-view FlashPix viewing transforms
-vignette geometry soften the edges of the image in vignette style
-virtual-pixel method access method for pixels outside the boundaries of the image
-wave geometry alter an image along a sine wave
-wavelet-denoise threshold removes noise from the image using a wavelet transform
-weight type render text with this font weight
-white-point point chromaticity white point
-white-threshold value force all pixels above the threshold into white
-write filename write images to this file
-write-mask filename associate a write mask with the image
Читайте также:  Как сделать ноутбук чтобы при выключался при закрытии крышки windows

© 1999-2021 ImageMagick Studio LLC

Источник

Оцените статью