Gimp
Содержание:
- Environment¶
- Инструменты преобразования
- Возможности
- Search system¶
- Intention¶
- What is my “GIMP profile” and where do I find it?¶
- Step 1¶
- Первый урок — Знакомство с GIMP
- Crop an Image¶
- Features¶
- Rotate and/or Flip an Image¶
- File formats¶
- Introduction to GIMP¶
- Description¶
- The Perl Server and stand-alone scripts¶
- Comparing images
- Splash Images¶
Environment¶
GIMP respects a number of environment variables.
- DISPLAY
- to get the default host and display number.
- GIMP2_DIRECTORY
- to get the name of the personal GIMP directory. If unset .gimp-2.6 is used. If this is an absolute path, it is used as is. If it is a relative path, it is taken to be a subdirectory of the home directory.
- GIMP2_DATADIR
- to get the base location for data files such as brushes and patterns. If unset /usr/share/gimp/2.0 is used.
- GIMP2_LOCALEDIR
- to get the base location for translations. If unset /usr/share/locale is used.
- GIMP2_PLUGINDIR
- to get the base location for plug-ins and modules. If unset /usr/lib64/gimp/2.0 is used.
- GIMP2_SYSCONFDIR
-
to get the location of configuration files. If unset /etc/gimp/2.0 is used.
On Linux GIMP can be compiled with support for binary relocatibility. This will cause data, plug-ins and configuration files to be searched relative to the location of the gimp executable file unless overridden by the environment variables mentioned above.
Инструменты преобразования
Инструменты преобразования используются для изменения изображения или слоя. К ним относятся:

|
|
У каждого инструмента есть диалог параметров и диалог информации для указания параметров.
Перемещение
Инструмент Перемещение используется для перемещения слоёв, плавающих выделений, направляющих и текстов.
Выравнивание
Инструмент Выравнивание используется для выравнивания слоев, относительно какого-то объекта изображения.
Кадрирование
Инструмент Кадрирование используется для обрезания частей изображения или слоя. Этот инструмент обычно используется для удаления краёв или ненужных областей.
Для использования инструмента нажмите внутри изображения и протяните по диагонали. Отпустите кнопку мыши. Все что попало в эту область останется после кадрирования, остальное будет удалено. При необходимости отрегулируйте кадрируемую область. Нажмите клавишу ENTER.
Вращение
Инструмент Вращение используется для поворота активного слоя, плавающего выделения или контура. При нажатии на изображение или выделение этим инструментом появится сетка поверх изображения и диалог Информация по вращению. Там можно выбрать ось вращения, отмеченной большой точкой, и угол вращения. Операции в окне диалога можно выполнить прямо на изображении нажатием и движением курсора мышки.
Масштаб
Инструмент Масштаб используется для изменения размера слоя, выделения или контура. При нажатии инструментом на изображении появится окно информации о масштабировании, позволяющее изменить ширину и высоту. В то же время поверх изображения появится сетка с обработчиками, позволяющими изменить эти размеры движением курсора. Маленький кружок в центре окно просмотра позволяет перемещать просмотр.
Наклон
Инструмент Наклон используется для перемещения одной части изображения, слоя, выделения или контура в одном направлении, а другой части – в противоположном. Например, горизонтальное искривление переместит верхнюю часть вправо, а нижнюю влево. Таким образом, прямоугольник станет ромбом. Это не вращение: изображение искажается. При нажатии инструментом на изображении появится окно информации по искривлению, где можно указать размер искажения по горизонтали и вертикали. Также поверх изображения появится сетка с обработчиками, позволяющими указать искривление движением курсора. При достижении результата, нажмите в окне информации кнопку Наклонить для закрепления эффекта.
Перспектива
Инструмент Перспектива используется для изменения перспективы активного слоя, краёв выделения или контура. При нажатии на изображении появится прямоугольная рамка или сетка вокруг выделения (или вокруг всего изображения, если нет выделения) с обработчиками по углам. Двигая обработчики, вы можете изменить перспективу. В то же время появится информация о преобразовании, позволяющая проверить правильность преобразования. Перемещение точки в центре позволяет изменить центр перспективы.
Зеркало
Инструмент Зеркало позволяет перевернуть слои или выделения горизонтально или вертикально. Когда выделение переворачивается, создаётся новый слой с плавающим выделением. Он также может создавать отражения.
|
Исходное изображение |
Применен инструмент Кадрирование |
Применен инструмент Вращение |
Применен инструмент Масштабирование |
|
Применен инструмент Наклон |
Применен инструмент Перспектива |
Применен инструмент Зеркало |
Возможности
Слайды показывают Кисти, Шаблоны и Градиенты, доступные для GIMP (Mac OS X Lion)
Работа с фотографиями
В GIMP присутствует набор инструментов цветокоррекции:
- кривые;
- уровни;
- микшер каналов;
- постеризация;
- тон-насыщенность;
- баланс цветов;
- яркость-контраст;
- обесцвечивание.
При помощи фильтров, инструментов, масок и слоёв с разными типами наложения (всего 22) можно:
- выравнивать заваленный горизонт;
- убирать искажения, вносимые оптикой;
- корректировать перспективу;
- выполнять клонирование объектов с учётом перспективы;
- кадрировать фотографии;
- удалять дефекты вроде пыли на матрице (штамп, лечебная кисть);
- имитировать использование различных цветофильтров;
- «вытаскивать» потерянную детализацию в тенях;
- многое другое.
Реализовано управление цветом.
Рисование
- несколько рисующих инструментов;
- свободно масштабируемые кисти;
- поддержка кистевой динамики;
- поддержка графических планшетов.
Экранные фильтры
Дополнительные возможности по коррекции изображений на протяжении всей работы реализованы в виде экранных фильтров. К ним относятся:
- имитация разных типов дальтонизма (протанопия, дейтеранопия, тританопия);
- гамма-коррекция;
- коррекция контраста;
- управление цветом.
Настраиваемый интерфейс
- плавающие диалоги легко группируются и перегруппируются;
- возможна полная перенастройка клавиатурных комбинаций, действий мыши, а также устройств ввода, таких как Griffin PowerMate (англ.)русск.;
- любое меню можно превратить в свободно перемещаемое окно (Linux/UNIX).
Автоматизация
Отсутствие средств автоматической записи сценариев компенсируется в GIMP большим числом языков, на которых можно писать сценарии:
- TinyScheme<span title=»Статья «TinyScheme» в русском разделе отсутствует»>ru</span>en, иначе Script-Fu (в комплекте с программой);
- Python (в комплекте с программой);
- Ruby;
- Perl;
- C# (GIMP# — gimp-sharp);
- Java (экспериментально, часть проекта gimp-sharp);
- Tcl (в настоящее время не поддерживается).
С помощью этих инструментов можно писать как интерактивные сценарии и модули для GIMP, так и создавать изображения полностью автоматически, например, генерировать «на лету» изображения для веб-страниц внутри программ CGI или выполнять пакетную цветокоррекцию и преобразование изображений. Следует отметить, что для пакетной обработки изображений всё же лучше подходят пакеты наподобие ImageMagick.
Недочёты, их решение и пути обхода
В настоящее время использование стабильной версии GIMP в коммерческом дизайне, полиграфии и фотографии сопряжено с рядом сложностей, а во многих случаях и вовсе невозможно:
- нет поддержки плашечных цветов (и палитры Pantone);
- нет полноценной поддержки цветовых моделей, CIELAB и CIE XYZ;
- нет поддержки HDRi и операторов отображения тонов;
- нет процедурных (корректирующих) слоёв и эффектов (стилей) слоёв;
Некоторые упомянутые недочёты уже устранены в разрабатываемой версии GIMP благодаря переходу на библиотеку GEGL, другие планируется устранить на следующем этапе разработки.
Search system¶
As GIMP keeps growing and getting more features, it becomes increasingly
difficult to locate this or that command in the user interface. This is
especially true when you are a new user who has yet to master image editing,
or an experienced user who is accustomed to a different application.
GIMP 2.10 comes with a search system that allows easily locating a command available in GIMP’s menu. Press the slash key (), type a keyword,
and choose the command that looks most applicable.
Contributors: Srihari Sriraman, Jehan Pagès…
Simplified bug reporting and crash recovery
We need good bug reports to make GIMP better for you, so we introduced a new
feature to watch and intercept critical errors and crashes, then generate a
useful error log that you can copy/paste to a bug report.
On development versions, the dialog will be raised on all kind of errors (even
minor ones). On stable releases, it will be raised only during crashes. The
default behavior can be customized in Edit > Preferences > Debugging.
Please note that we still need you to provide context, e.g. what you were doing
when a crash occurred. A step-by-step description of how to reproduce this bug
will be most helpful.
Additionally, in case of a crash, GIMP will now attempt to backup all images
with unsaved changes, then suggest to reopen them the next time you start the application.
We cannot guarantee 100% success, but it will succeed sometimes, and this might
rescue your unsaved work!
Contributors: Jehan Pagès…
Intention¶
On this page, the first section of our ever growing (?) collection of tutorials, I will demonstrate the basic operation you will need to perform over and over again in your life as a computer artist: Generate isolated parts of a picture and combine them with a random background. What we want to achieve in this example is to generate a 3-dimensional text logo flying (and movable) over the background (a simple uni-color layer in our case, but you will easily see that you could use any other (stack of) layers/images instead. Start with a plain white picture, black as the foreground color and open the layer dialog!
What is my “GIMP profile” and where do I find it?¶
The “GIMP profile” is a directory/folder (actually a directory tree) where GIMP keeps information that pertains to you, the user:
- your windows and dialogs setup
- your settings and presets for some tools
- your keyboard shortcuts
- your brushes, gradients, palettes, patterns, fonts, scripts, plugins and brush dynamics (as opposed to those installed for the benefits of all users).
Locating the GIMP (2.8) profile
Since it is a personal folder, GIMP keeps it with others files that also belong to you, usually:
- In Windows XP:
(ie, a “sibling” of “Application Data” and “My Documents”)
- In Vista, Windows 7 and later versions:
(ie, a “sibling” of “Application Data” and “My Documents”)
- In Linux:
(a.k.a. )
- In OSX:
or possibly
(this could depend on the GIMP build you use).
The part is of course version-dependent (or you may still be using ).
If you run several versions in parallel, you will have a profile for each, i.e., distinct profiles for GIMP 2.6 and GIMP 2.8, while all the successive updates to GIMP 2.8 will use the same profile.
If you don’t find it in the locations above
- If you are on Linux or OSX, keep in mind that the leading dot in the name makes many tools “omit” to display it,
so you may have to explicitly ask your file explorer to display hidden files to navigate to it. - On all systems (and especially Windows versions), it can be elsewhere for several reasons,
for instance because the user profile has been moved to another partition/drive (especially with “roaming” users).
Here are two tricks to find it (they both assume that GIMP can run):
Trick #1
- Edit → Preferences and open the Folders tree in the left pane of the dialog.
- If you click on any of the folders (for instance, Brushes), the right pane will normally display two folders:
- The non-writable one is the one that holds system-wide features (brushes in this case), located somewhere in the GIMP installation tree
- The writable one is your own brushes folder in your GIMP profile: the GIMP profile is its parent folder.
Trick #2
- Open Filters/Python-fu/Console
- Enter this: and strike
When to use the GIMP profile
Your GIMP profile is the right place to install additional material (scripts, plugins, brushes, palettes, fonts, gradients…).
It is a much better place than the system GIMP installation folder:
- Installing things there will not require admin privileges
- The additional items will not be wiped out by a GIMP re-installation
- They are more likely to be backed up since they are part of the user’s data
Repairing the GIMP profile
GIMP Startup failures can be caused by profile problems. In that case it is pointless to re-install GIMP,
since the re-installed version will re-use the existing profile and therefore fail in the same way.
It is usually much more efficient to just rename the profile (to , for instance) and restart GIMP.
GIMP will recreate a new profile directory on startup, which should fix any problems.
You can then copy your add-ons subdirectories to the new profile, checking periodically that GIMP will still start
with that modified profile.
GIMP Tutorial — Your GIMP Profile and You by Ofnuts is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Step 1¶
We’ll create a very simple web banner. Let’s start with a new image 468×60 px. Use white as the background color. Create new transparent layer. Select the whole image with Ctrl+A and fill it with black (Ctrl+,). Shrink the selection by 1 px () and delete the selection with Ctrl+K. We created a 1 px frame around out banner.
Now it’s time to put our logo or the main theme picture into the banner. I have prepared a masked-out flower you see on the picture on the left. I just pasted the flower below the border frame, used alpha to selection, created an empty layer below it and filled the selection with black using Ctrl+,. After that I blurred the shadow using Gaussian blur RLE and offset it by 2px to bottom right. I couldn’t resist adding the interlace effect using and a layer mask. In that layer mask i applied a b/w gradient, so that the left of the flower is not interlaced.
This part of the tutorial is not the key element, so feel free to experiment. Once you’re ready flatten the image using the .
Первый урок — Знакомство с GIMP
И так изображение у нас открыто. И как помните из задания: необходимо выделить объект на переднем плане, а на переднем плане у нас красивый цветок. На панели инструментов выбираем инструмент «Свободное выделение» или как его еще называют «Лассо». Теперь аккуратно используя мышь, обводим по контуру цветок. Не торопитесь, чем больше контрольных участков у вас получится, тем четче будет выделен объект.
Чтобы увеличить изображение зажмите клавишу Ctrl и с помощью колесика мыши отрегулируйте необходимый масштаб.
Более подробно о различных способах выделения в гимпе читайте в статье методы и способы выделения в гимпе, от простого к сложному.
854
Выделение цветка заканчиваем на начальной точки, с которой мы начали обводить.(просто щелкаем мышкой по ней). При этом наше выделение сменится на так называемую «муравьиную дорожку».
Теперь воспользуемся еще одной командой для улучшения выделения. Нам необходимо смягчить края у выделения, размыть их немного и в этом нам поможет инструмент «Растушевать» из пункта меню Выделение.
Значение устанавливаем на 5 пикселей.
Молодцы. Копируем выделенный фрагмент цветка через меню Правка | Копировать. Теперь вставляем скопированный цветок через Правка | Вставить. И как вы заметите у нас в окне Слои появился слой под названием Плавающее выделение.
Плавающее выделение — это временный слой, он появляется всегда, когда вы вставляете из буфера обмена картинку или фрагмент изображения. Далее щелкаем правой кнопкой мыши по плавающему слою и из выпавшего контекстового меню выбираем команду — Создать слой.
Визуально нечего не произошло, а на самом деле цветок теперь содержится в новом верхнем слое, и что бы показать это выключим видимость фонового нижнего слоя, щелкнув на пиктограмму глаза напротив слоя.
Таким образом мы отделили объект на переднем плане от фона. Теперь создадим прозрачный слой через меню Слой | Создать слой
или нажав на соответствующую пиктограмму
окне Слои.
Данный слой у нас послужит новым фоном для слоя с цветком. Усложнять наше первое задание слишком не будем, и просто возьмем и зальем данный слой градиентной заливкой. Для этого выбираем инструмент Градиент
Чтобы выбрать нужный цвет нажимаем на соответствующий прямоугольник : верхний прямоугольник — это цвет переднего плана, а позади него прямоугольник — цвет фона. Откроется диалоговое окно выбора цвета, где мышкой можно выбрать нужный цвет или ввести кодовое обозначение (HTML-разметка) нужного цвета.
Далее необходимо уменьшить изображение, для этого выбираем Изображение|Размер изображения
и вводим параметры 1024×768 пикселей. Я ввожу данные значения для примера. Вы можете уменьшить фотографию до других параметров ( в зависимости от выбранного первоначального изображения).
И заключительный этап урока для начинающих это сохранение готового изображения через меню Файл| Сохранить как..
И изменяем расширение изображения с JPEG на PNG в поле Имя. Далее нажимаем кнопку «Сохранить»
Откроются еще два окна. В первом нажимаем «Экспорт», во втором окне «Сохранить»
На этом наше первое знакомство с GIMP завершено
Спасибо за внимание!. Не забудьте пройти небольшой тест по компьютерной графике
Не забудьте пройти небольшой тест по компьютерной графике.
Тест №1 по компьютерной графике
Предлагаю Вам пройти небольшой тест по компьютерной графике и проверить свои знания
ПРОЙТИ ТЕСТ
Вопрос:
Ваш ответ:
Правильный ответ:
ДАЛЕЕ
Crop an Image¶
There are numerous reasons you may want to crop an image. You may want to remove useless borders or information for aesthetic reasons, or you may want the focus of the final image to be of some particular detail for instance.
In a nutshell, cropping is just an operation to trim the image down to a smaller region than what you started with:
Original image (left), cropped image (right).
The procedure to crop an image is straightforward. You can either get to the Crop Tool through the tools palette:
Crop Tool on the Tools Palette.
Or you can access the crop tool through the menus:
Tools → Transform Tools → Crop
Once the tool is activated, you’ll notice that your mouse cursor on the canvas will change to indicate the Crop Tool is being used.
Now you can Left-Click anywhere on your image canvas, and drag the mouse to a new location to highlight an initial selection to crop. You don’t have to worry about being exact at this point, as you will be able to modify the final selection before actually cropping.
Initial pass with the Crop Tool.
Crop Tool options (left), cropping on the canvas (right).
Features¶
We switched to a dark user interface theme and a symbolic icon theme by default
in version 2.10. If you absolutely want to revert it, here is what you do:
Go to and change the theme from Dark
to System.
Then go to and change the theme
from Symbolic to Legacy.
Changes will apply immediately. Click OK to confirm.
When will GIMP support HDR imaging and processing with 16bit per color channel precision?
GIMP 2.10 was released in April 2018 and is the first version of the program
to feature processing with precision of 16-bit and 32-bit per color channel.
Will GIMP open raw (.NEF, .CR2 etc.) files from my camera?
Starting with version 2.10, GIMP features plug-ins for using
darktable and
RawTherapee to process raw images, as well as a
preference for a default raw processing plug-in.
Yes, better support for CMYK has been on our roadmap for a long time. One of the
ideas, how we want to make this work, was introduced by user interaction
architect Peter Sikking at Libre Graphics Meeting 2009 and later —
in his two-part article in his company’s blog:
,
. Please
take some time to read up on that.
We needed to finalize transition to the new image processing engine, GEGL,
before attemtping to introduce features like CMYK support. Now that it is
complete, initial work on CMYK support has been done in the babl and GEGL
libraries that GIMP relies on. This is partially
funded by the GIMP community,
you can join in, too.
Once we finish some more work on color management in GIMP, it will be a good
idea to start exposing CMYK in the user interface. We have no timeline on this.
Also, please note that we are not planning advanced features such as GCR support
for now. This will most likely require a new dedicated developer in the team.
Should a new developer join the team to specifically work on
CMYK-related features, we will do our best to help him/her to complete this
project and get it to our users as soon as possible.
We realize that some changes are disruptive to some groups of users,
especially those who got used to GIMP as an image editor for doing quick fixes
to lossy files such as JPEG, PNG etc. (i.e. files that cannot store layers,
masks, custom channels, paths).
However, adding a switch for every change we make adds numerous levels of
complexity that we’d rather avoid. Additionally, it would lead to dramatically
changing the way we mean GIMP to work. Hence we respectfully disagree to make
extra behaviour switches.
At the same time, if you don’t wish to abandon GIMP completely, we recommend
having a look at the
Saver and Save/export clean plug-ins
by Akkana Peck, as well as at various GIMP forks on GitHub, although typically
they aren’t maintained up to date with regards to bugfixes.
Rotate and/or Flip an Image¶
There may be a time that you would need to rotate an image. For instance, you may have taken the image with your camera in a vertical orientation, and for some reason it wasn’t detected by GIMP as needing to be rotated (GIMP will normally figure this out for you, but not always).
There may also be a time that you’d like to flip an image as well. These commands are grouped together under the same menu item:
Image → Transform
Flip an Image
If you want to flip your image, the Transform menu offers two options, Flip Horizontally, or Flip Vertically. This operation will mirror your image along the specified axis. For example, here are all of the flip operations shown in a single image:

All flips applied to base image (top left).
Rotate an Image
Image rotation from the Transform menu is contrained to either 90° clockwise/counter-clockwise, or 180°.
Don’t mis-interpret this to mean that GIMP cannot do arbitrary rotations (any angle). Arbitrary rotations are handled on a per-layer basis, while the image rotation described here is applicable to the entire image at once.

Original (top left), 90° clockwise (top right)
90° counter-clockwise (bottom left), 180° (bottom right)
File formats¶
The highlight of this release is clearly the contributions on file
format plug-ins.
HEIF: improved HEIC and newly added AVIF support
AVIF is the HEIF variant using AV1 compression (instead of HEVC in the
same HEIF container format, which is the default and also called HEIC).
This format was highly awaited as being an open, royalty-free, video
coding format developed by the
Alliance for Open Media.
AVIF is already supported on the web in Firefox (experimentally, you
must enable in ), Chrome and Opera,
which makes it a serious contender as a web image format.
It is now supported by GIMP, both for import and export.
Not only this, but HEIF files (both AVIF and HEIC) can now be imported
and exported in high bit depth (10- and 12-bit per channel).
GIMP 2.10.20 brings AVIF support, as well high-bit depth support.
It will also import NCLX profiles and metadata.
And finally, NCLX color profiles and metadata will now be properly imported.
These changes all happened thanks to the awesome contributions of Daniel Novomesky.
PSP
The plug-in for reading PSP (Paint Shop Pro) files has received numerous
bug fixes and improvements. Raster layers from PSP images over
version 6 are now supported, as well as 16-bit integer, grayscale, and
indexed images.
Furthermore, PSP blend modes are now better converted to GIMP layer
modes for correct rendering.
The importer is also much more robust and is even able to fix errors of
some files which may have been wrongly exported by third party software.
It also handles some edge cases like zero-length layer names better.
All these improvements were made by Jacob Boerema, one of GIMP newest core contributors.
TIFF
Multi-layer TIFF export got improved by allowing to crop layers to image
bounds in the exported image. Indeed, TIFF has no concept of global image
bounds, only layer bounds. Hence cropping the layers is the only way to
enforce the image bounds.
Obviously, this cropping may or may not be what you wanted and perhaps
you were expecting layers of various sizes. This is why the feature is
available as a new optional Crop layers to image bounds checkbox in
the export dialog.
There have been other bug fixes and improvements in the TIFF plug-in
as well.
BMP, DDS, JPEG, WebP, XPM…
Other file format supports were improved. In particular:
-
BMP always include color masks when exporting BMP with color space
info, as mandated by BITMAPV5HEADER specification. -
DDS import is now a bit more permissive, allowing to load some files
with invalid header flags regarding compression, while we are able to
know the right compression from other flags. This allows to recover
invalid DDS files exported by other software. - JPEG and WebP detection improved.
-
XPM does not export a “None” (transparent) color when unused.
Exporting an unused color was not a bug per-se but was not very well
handled by some third party software.
Introduction to GIMP¶
GIMP is an acronym for GNU Image Manipulation Program. It is a freely distributed program for such tasks as photo retouching, image composition and image authoring.
It has many capabilities. It can be used as a simple paint program, an expert quality photo retouching program, an online batch processing system, a mass production image renderer, an image format converter, etc.
GIMP is expandable and extensible. It is designed to be augmented with plug-ins and extensions to do just about anything. The advanced scripting interface allows everything from the simplest task to the most complex image manipulation procedures to be easily scripted.
GIMP is written and developed under X11 on UNIX platforms. But basically the same code also runs on Windows and macOS.
Description¶
GIMP is the GNU Image Manipulation Program. It is used to edit and manipulate images. It can load and save a variety of image formats and can be used to convert between formats.
GIMP can also be used as a paint program. It features a set of drawing and painting tools such as airbrush, clone, pencil, and paint brush. Painting and drawing tools can be applied to an image with a variety of paint modes. It also offers an extensive array of selection tools like rectangle, ellipse, fuzzy select, bezier select, intelligent scissors, and select by color.
GIMP offers a variety of plug-ins that perform a variety of image manipulations. Examples include bumpmap, edge detect, gaussian blur, and many others. In addition, GIMP has several scripting extension which allow for advanced non-interactive processing and creation of images.
GIMP ships with a second binary called gimp-console. This binary is a console-only version and behaves as if gimp was called with the —no-interface command-line option.
On platforms with the D-Bus message bus system, GIMP will by default check if an instance is already running in this user session. If it detects that, it will pass all filenames given on the command-line to the already running GIMP instance and quit.
The Perl Server and stand-alone scripts¶
So far the scripts have all been started from the menu structure within GIMP. But using Gimp::Fu there is another possibility, and that is to run the scripts from the command line, as a normal Perl program. When run this way the script tries to connect to the Perl-Server, and if it fails it will launch a GIMP of its own. If you plan to run several scripts this way, it is obviously much faster to run the Perl-Server since launching GIMP takes quite a bit of time. The Perl-Server may be started from the Filters/Perl menu.
When a Gimp::Fu script is run from the command line, the result is the same as when it is run through the menus, except that it may be run with the --output parameter. This will save the result to a file instead of displaying it within GIMP. This is great for batch creation of logos, etc.
The filename for the --output has some special magic that allows to set some special image saving parameters, like interlace, quality factor, etc. See the for more detail
Here are two invocations of the scripts declared above, but with output written to a jpg file and a png file.
| perl-gimp-from-shell |
|---|
uni -o /tmp/uni.png --size 100 --color purple basic-logo --font 'utopia 100' -o /tmp/bl.ppm --size 20 --text "Perl rules" |
Another important use of this interface is that it enables running the Perl debugger on the perl scripts.
10.1. A shell for Gimp-Perl
When using the Perl-Server it is not necessary to use Gimp::Fu and the podregister function. Instead you may call Gimp::on_net, which takes as a parameter a reference to a sub routine that is called when your script has connected to a GIMP (or started one up).
For a simple but powerful example of the use of the Gimp without Fu, here is a an interactive Gimp-Perl shell that may be run from the command line:
pg-shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#!/usr/bin/perl
# An interactive command line shell to GIMP.
use Gimp;
use Term::ReadLine;
Gimp::on_net {
$term = new Term::ReadLine("Gimp");
while( defined ($_ = $term->readline("Gimp> "))) {
$res = eval($_) . "\n";
print("Error: $@"), next if $@;
print "\n";
Gimp->displays_flush();
}
};
exit Gimp::main;
|
Here is an example of an interactive session with this shell:
| interact |
|---|
Gimp> $img = Gimp::Image->new(100,100,RGB) Gimp> $drw = $img->layer_new(100,100,RGB_IMAGE, "bg", 100, NORMAL_MODE) Gimp> $img->insert_layer($drw,-1, 0) Gimp> Gimp::Display->new($img) Gimp> $drw->edit_clear Gimp> print Gimp::Image->list Gimp::Image->existing(1) |
Comparing images
image.hash();
By default the hash is returned as base 64. The hash can be returned at another base by passing a number from 2 to 64 to the method:
image.hash(2);
There are 18,446,744,073,709,551,615 unique hashes. The hamming distance between the binary representation of these hashes can be used to find similar-looking images.
To calculate the hamming distance between two Jimp images based on their perceptual hash use:
Jimp.distance(image1, image2);
var diff =Jimp.diff(image1, image2, threshold);diff.image;diff.percent;
Using a mix of hamming distance and pixel diffing to compare images, the following code has a 99% success rate of detecting the same image from a random sample (with 1% false positives). The test this figure is drawn from attempts to match each image from a sample of 120 PNGs against 120 corresponding JPEGs saved at a quality setting of 60.
var distance =Jimp.distance(png, jpeg);var diff =Jimp.diff(png, jpeg);if(distance <.15||diff.percent<.15){}else{}
You can also calculate the raw pHash (no padding or custom base). You can then use this in to calculate the hash distance from a loaded image.
consthash1=image1.pHash();consthash2=image2.pHash();image2.distanceFromHash(hash1);Jimp.compareHashes(hash1, hash2);
Splash Images¶
GIMP comes with a default image for the splash screen but it allows system administrators and users to customize the splash screen by providing other images. The image to be used with the splash screen is chosen as follows:
-
GIMP tries to load a random splash screen from the directory $HOME/.gimp-2.6/splashes.
-
It then falls back to using $HOME/.gimp-2.6/gimp-splash.png.
-
If the user didn’t install any custom splash images, a random image is picked from /usr/share/gimp/2.0/splashes.
-
As a last resort, GIMP uses the default splash image located at /usr/share/gimp/2.0/images/gimp-splash.png.

