Linux convert resize image

Shell script to resize image, convert image format in Linux

Table of Contents

All of us download photos from our phones and cameras. Before we e-mail an image or post it to the Web, we may need to resize image or perhaps change the format of image. We can use scripts to perform batch image resize and other tasks using ImageMagick

In this article we will use a script to perform below tasks in bulk

  • change image size
  • convert image format

ImageMagick

ImageMagick is a free and open-source software suite for displaying, converting, and editing raster image and vector image files. It can read and write over 200 image file formats.

Before we go to our shell script, I will show some examples related to ImageMagick

Convert Image Format

To convert image format we will use covert tool from ImageMagick.

Here we are converting JPG format image to PNG.

Resize Image

We can resize an image by specifying the scale percentage or the width and height of the output image. To resize an image by specifying WIDTH or HEIGHT, use this:

If either WIDTH or HEIGHT is missing, then whatever is missing will be automatically calculated to preserve the image aspect ratio:

Sample Shell Script

Let us jump to our shell script to resize image in a batch.

The batch_image_resize.sh script accepts these arguments:

  • -source: This specifies the source directory of the images.
  • -dest: This specifies the destination directory of the converted image files. If -dest is not specified, the destination directory will be the same as the source directory.
  • -ext: This specifies the target file format for conversions.
  • -percent: This specifies the percentage of scaling.
  • -scale: This specifies the scaled width and height.
  • Both the -percent and -scale parameters may not appear.
  • The script starts by checking the number of command arguments. Either four, six, or eight parameters are valid.

Now let us execute the batch_image_rezize.sh script to resize image based on percentage. Before calling the script below is the size of all my images

I will create a new directory where I will store my resized images

Now execute the script to resize image to 80%

Now verify the new size which we see that the size of image is reduced to 80% of the original size.

How the script works?

  • The command line is parsed with a while loop and the case statement and values are assigned to appropriate variables.
  • $# is a special variable that contains the number of arguments. The shift command shifts the command arguments one position to the left. With this, every time the shifting happens, we can access the next command argument as $1 rather than using $1, $2, $3, and so on.
  • The case statement is like a switch statement in the C programming language. When a case is matched, the corresponding statements are executed. Each match statement is terminated with ;; . Once all the parameters are parsed into the variables percent , scale , source_dir , ext , and dest_dir , a for loop iterates through each file in the source directory and the file is converted.
  • Several tests are done within the for loop to fine-tune the conversion.
  • If the variable ext is defined (if -ext is given in the command argument), the extension of the destination file is changed from source_file.extension to source_file.$ext .
  • If the -dest parameter is provided, the destination file path is modified by replacing the directory in the source path with the destination directory.
  • If -scale or -percent are specified, the resize parameter ( -resize widthx or -resize perc% ) is added to the command.
Читайте также:  Статический маршрут windows что это

Related searches: linux resize image photo. linux image converter. script to resize image. magick resize. convert resize. imagemagick reduce file size. imagick png compression. batch downsize images. resize jpeg batch. linux convert image format from png to jpg.

Источник

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-предыдущее имя файла.

Читайте также:  Windows live id для nokia lumia

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

В общем утилита 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.

Источник

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.
Читайте также:  Linux terminal how to root

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:

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.

Источник

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