Linux resize image console

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):

Читайте также:  Что такое bitlocker windows 10 как отключить

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 очень удобна и хороша в работе. А главное она сжимает практически без потерь качества, что немаловажно. Конечно она не подойдет для тех кто терпеть не может консоль. Но я для других — очень даже ничего:)
Пользуйтесь!;)

Источник

How to resize an image through the terminal? [duplicate]

I have Ubuntu 10.04. I have converted image through terminal using the following command:

But I want to resize the height and width of the converted image. Is there any way to do this?

4 Answers 4

Same command, with an extra option:

To resize multiple files, you can try the following command (as suggested by @test30)

If you want CLI only:

If you wanna try GUI:

It adds two context menu items in nautlius so you can right click and choose «Resize Image».(The other is «Rotate Image»).

You can do a whole directory of images in one go if you like and you don’t even have to open up an application to do so.

Since Ubuntu ships with Python, you can also use a Python script to achieve this with a little more control over what happens — see this stackoverflow question for example scripts. Those examples use just the standard library.

Script #1

And another example where you only have to specify the width (as the width variable):

Script #2

Now, how to do this through the terminal.

Paste one of those blocks of code into the text editor. Ctrl+x to exit (say yes to save changes).

To use Script #1:

To use Script #2:

You must be in the same directory as the picture files for both of these scripts. The first one shrinks the image to 128×128 pixels. The second script makes it 300 pixels wide and calculates the proportional height. This is more of a Python answer, but it is done all through the terminal technically.

Источник

Batch Resize Images using Linux Command Line and Imagemagick

Large images means a large page size which means slow WordPress page load times for users. The most common culprit is image size or lack of compression. If you never had any image size restrictions or automatic resizing on your site, it can be extremely convenient to batch resize those images in Linux.

This guide shows you how to batch resize jpg and png files using Imagemagick on Ubuntu or Debian. If you want to install Imagemagick on CentOS see this guide.

Batch Resize Images using Linux Command Line and Imagemagick

First we need to install Imagemagick from the repository on Debian or Ubuntu

We can use the identify command to get the width ( %w ) and height ( %h )

You will see the resolution, width is first then height.

You can resize the image if it is larger than the specified dimensions. This will automatically preserve the aspect ratio of the image too.

Note that this overwrites your original image!

Check the image was resized

Now we can move on to batch resizing

Batch Resize Images with Linux with Imagemagick

Create the following script

Paste the script below, remember to change the FOLDER variable!

FOLDER is the absolute path to your image folder

WIDTH is the max width and HEIGHT is the max height.

It will overwrite your original images so make sure you have a backup before running this!

Ctrl+X, Y and Enter to save and exit.

Check the folder size

Check output size

Screen will ensure the batch command keeps on running even if your SSH session is terminated.

Create a new screen session, press space or enter at the intro screen

Читайте также:  Kvm настройка для windows

Execute the script

Detach the screen with Ctrl+A and pressing D (detach).

You can use the top command and look for jpegoptim processes once in a while.

Reattach the screen like so

Check the folder size again

You should see an improvement

Make sure to compress your images with lossless (guide) or lossy compression (guide).

If you need to do some more advanced find commands that use regex this should help.

Источник

How to Convert Images Using Linux

Use ImageMagick to covert images in the command line

What to Know

  • Install the ImageMagick utility using terminal. In Debian, Ubuntu, or Mint, enter sudo apt install imagemagick.
  • To convert an image, the command is convert [input options] input file [output options] output file.
  • To resize an image, enter convert [imagename].jpg -resize [dimensions] [newimagename].jpg.

This guide shows how to manipulate images using the Linux command line. You will find out how to resize an image both in terms of file size and in scale. You will also learn how to convert between multiple file types such as from JPG to PNG or GIF to TIF.

Install ImageMagick

The convert command isn’t a default Linux system utility, and it doesn’t come with most distributions. There’s a good chance that you’ll need to install it.

Convert comes from ImageMagick, a popular image manipulation utility used by a lot of applications. Begin by installing it on your system. Open a terminal window, and run the command matching your distribution.

Debian/Ubuntu/Mint

Fedora/CentOS

OpenSUSE

Arch Linux/Manjaro

The Convert Command

The convert command is used to convert an image. The format is as follows:

How to Resize an Image

If you are going to include an image on a webpage and you want it to be a particular size then you could use some CSS to resize the image.

It is actually better though to upload the image as the correct size in the first place and insert it into the page.

This is of course just one example why you might want to resize an image.

To resize an image use the following command

For example, to convert an image to be 800×600 you would use the following command:

If by converting to the specified dimensions the aspect ratio will be messed up the image will be resized to the closest ratio.

To force the conversion to be the exact size, use the following command:

You don’t have to specify the height and the width as part of the resize command. For example, if you want the width to be 800 and you don’t care about the height you can use the following command:

To resize an image to be a specified height use the following command:

How to Convert From One Image Format to Another

If you have a JPG file and you wish to convert it to a PNG then you would use the following command:

You can combine many different file formats. For example:

How to Adjust the File Size for an Image

There are a number of ways to change the physical file size of an image.

  1. Change the aspect ratio (make it smaller)
  2. Change the file format
  3. Change the compression quality

Reducing the size of the image will make the file size smaller. In addition, using a file format that includes compression such as JPG will enable you to reduce the physical file size.

Finally adjusting the quality will make the physical file size smaller.

The previous 2 sections showed you how to adjust the size and file type. To compress the image try the following command:

The quality is specified as a percentage. The lower the percentage the smaller the output file but obviously the final output quality is not as good.

How to Rotate Images

If you have taken a photo in portrait but you want it to be a landscape image you can rotate the image using the following command:

You can specify any angle for rotation.

For example, try this out:

Convert Command Line Options

There are dozens of command line options that can be used with the convert command as shown here:

Читайте также:  Как поменять версию java windows

Options are processed in command line order. Any option you specify on the command line remains in effect for the set of images that follows, until the set is terminated by the appearance of any option or -noop. Some options only affect the decoding of images and others only the encoding. The latter can appear after the final group of input images.

For a more detailed description of each option, see ImageMagick.

Источник

Resize Images with Right Click on Ubuntu and Other Linux Distributions [Quick Tip]

Last updated April 15, 2020 By Abhishek Prakash 75 Comments

Brief: A Quick tip that shows how to resize images with right click menu in Linux quickly. The trick should work on any Linux distribution that uses Nautilus file manager.

How do you resize an image on Linux? Do you use GIMP or Shutter? Or perhaps you use ImageMagick in the terminal.

As I often need to resize the image before uploading them on It’s FOSS, Shutter was my favorite tool for this task until now. Shutter is an excellent screenshot tool that allows some quick editing features. However, if you just need to change the size, length and width of an image, opening an entire tool and going through menu options can be saved by using a nifty Nautilus plugin.

What’s Nautilus? Nautilus is a file manager used by GNOME and several other desktop environments. This is where you visually see your files. It’s equivalent to Windows Explorer in Linux.

There are several Nautilus plugins available that enhance its capability. They are not installed by default as they server specific purpose and users can choose to install them as per their needs.

One such Nautilus plugin is called Image Manipulator and it allows you to rotate or resize images by right-clicking on an image and choosing the option of rotating or resizing.

Quickly resize images with right click in Linux

Before you try to install the Nautilus plugin for quickly resizing images, I advise that you verify if your Linux system uses Nautilus file manager or not. To check that, use the command below:

If you get an output with version numbers, you have Nautilus file manager on your system. Else, your Linux distribution is using some other file manager.

You would also need ImageMagick because this plugin uses basically uses ImageMagick for image manipulation:

Once you have made sure that you have Nautilus file manager on your system, you can install the plugin using the command below:

If you are using Fedora, Arch or other non-Debian Linux, you can use your distribution’s package installing command.

Once installed, restart Nautilus using the command below:

Now if you right click on an image, you’ll see two new options of resize and rotate in the context menu.

You can choose the resize option to resize the image right from the right-click menu quickly. It will present you a few options for resizing the image.

As far as the custom size goes, though it doesn’t show, it retains the aspect ratio based on the width. So if you have a 1000×500 px image and you are trying to assign it a custom size of 800×300, the converted image will be 800×400, maintaining the original 2:1 ratio.

By default, it adds “.resized” to the name of the original image. This way your original image is not impacted and you get an additional resized imaged. You can change this behavior by choosing the ‘Resize in place’ option and the resized image will replace the original image.

It might not be a path-breaking trick but it does save you a few clicks.

To remove the plugin, you can use the command below:

And then restart the Nautilus. Simple!

Quickly resize images in elementary OS

This article inspired It’s FOSS reader Peter Uithoven to create a similar plugin for elementary OS users. You can get it from elementary OS app center.

I hope you liked this quick tip. If you know some neat little trick, do share with rest of us.

Like what you read? Please share it with others.

Источник

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