• Stars
    star
    929
  • Rank 49,172 (Top 1.0 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 4 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

CLI image optimization tool

@funboxteam/optimizt

Optimizt avatar: OK sign with Mona Lisa picture between the fingers

npm

Optimizt is a CLI tool that helps you prepare images during frontend development.

It can compress PNG, JPEG, GIF and SVG lossy and lossless and create AVIF and WebP versions for raster images.

По-русски

Rationale

As frontend developers we have to care about pictures: compress PNG & JPEG, remove useless parts of SVG, create AVIF and WebP for modern browsers, etc. One day we got tired of using a bunch of apps for that, and created one tool that does everything we want.

Usage

Install the tool:

npm i -g @funboxteam/optimizt

Optimize!

optimizt path/to/picture.jpg

Command line flags

  • --avif — create AVIF versions for the passed paths instead of compressing them.
  • --webp — create WebP versions for the passed paths instead of compressing them.
  • -f, --force — force create AVIF and WebP even if output file size increased or file already exists.
  • -l, --lossless — optimize losslessly instead of lossily.
  • -v, --verbose — show additional info, e.g. skipped files.
  • -c, --config — use this configuration, overriding default config options if present.
  • -o, --output — write result to provided directory.
  • -V, --version — show tool version.
  • -h, --help — show help.

Examples

# one image optimization
optimizt path/to/picture.jpg

# list of images optimization losslessly
optimizt --lossless path/to/picture.jpg path/to/another/picture.png

# recursive AVIF creation in the passed directory
optimizt --avif path/to/directory

# recursive WebP creation in the passed directory
optimizt --webp path/to/directory

# recursive JPEG optimization in the current directory
find . -iname \*.jpg -exec optimizt {} +

Differences between Lossy and Lossless

Lossy (by default)

Allows you to obtain the final image with a balance between a high level of compression and a minimum level of visual distortion.

Lossless (--lossless flag)

When creating AVIF and WebP versions, optimizations are applied that do not affect the visual quality of the images.

PNG, JPEG, and GIF optimization uses settings that maximize the visual quality of the image at the expense of the final file size.

When processing SVG files, the settings for Lossy and Lossless modes are identical.

Configuration

JPEG, PNG, WebP, and AVIF processing is done using sharp library, while SVG is processed using svgo utility.

For optimizing GIFs, gifsicle is used, and for converting to WebP, gif2webp is used.

💡 Lossless mode uses Guetzli encoder to optimize JPEG, which allows to get a high level of compression and still have a good visual quality. But you should keep in mind that if you optimize the file again, the size may decrease at the expense of degrading the visual quality of the image.

The default settings are located in .optimiztrc.js, the file contains a list of supported parameters and their brief description.

To disable any of the parameters, you should use false for the value.

When running with the --config path/to/.optimiztrc.js flag, the settings from the specified configuration file will be used for image processing.

When running normally, without the --config flag, a recursive search for the .optimiztrc.js file will be performed starting from the current directory and up to the root of the file system. If the file is not found, the default settings will be applied.

Integrations

External Tool in WebStorm, PhpStorm, etc

Add an External Tool

Open Preferences → Tools → External Tools and add a new tool with these options:

  • Program: path to the exec file (usually simply optimizt)
  • Arguments: desired ones, but use $FilePath$ to pass Optimizt the path of the selected file or directory
  • Working Directory: $ContentRoot$
  • Synchronize files after execution: ✔️

Set other options at your discretion. For example:

As you see on the screenshot above, you may add several “external tools” with the different options passed.

How to use

Run the tool through the context menu on a file or directory:

Shortcuts

To add shortcuts for the added tool go to Preferences → Keymap → External Tools:

Tasks in Visual Studio Code

Add Task

Run >Tasks: Open User Tasks from the Command Palette.

In an open file, add new tasks to the tasks array, for example:

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "label": "optimizt: Optimize Image",
      "type": "shell",
      "command": "optimizt",
      "args": [
        "--verbose",
        {
          "value": "${file}",
          "quoting": "strong"
        }
      ],
      "presentation": {
        "echo": false,
        "showReuseMessage": false,
        "clear": true
      }
    },
    {
      "label": "optimizt: Optimize Image (lossless)",
      "type": "shell",
      "command": "optimizt",
      "args": [
        "--lossless",
        "--verbose",
        {
          "value": "${file}",
          "quoting": "strong"
        }
      ],
      "presentation": {
        "echo": false,
        "showReuseMessage": false,
        "clear": true
      }
    },
    {
      "label": "optimizt: Create WebP",
      "type": "shell",
      "command": "optimizt",
      "args": [
        "--webp",
        "--verbose",
        {
          "value": "${file}",
          "quoting": "strong"
        }
      ],
      "presentation": {
        "echo": false,
        "showReuseMessage": false,
        "clear": true
      }
    },
    {
      "label": "optimizt: Create WebP (lossless)",
      "type": "shell",
      "command": "optimizt",
      "args": [
        "--webp",
        "--lossless",
        "--verbose",
        {
          "value": "${file}",
          "quoting": "strong"
        }
      ],
      "presentation": {
        "echo": false,
        "showReuseMessage": false,
        "clear": true
      }
    }
  ]
}

How to use

  1. Open the file for processing using Optimizt, it should be in the active tab.
  2. Run >Tasks: Run Task from the Command Palette.
  3. Select the required task.

Shortcuts

You can add shortcuts for a specific task by run >Preferences: Open Keyboard Shortcuts (JSON) from the Command Palette.

An example of adding a hotkey to run the "optimizt: Optimize Image (lossless)" task:

// Place your key bindings in this file to override the defaults
[
  {
    "key": "ctrl+l",
    "command": "workbench.action.tasks.runTask",
    "args": "optimizt: Optimize Image (lossless)"
  }
]

Plugin for Sublime Text 3

You’ll find the user settings directory in one of the following paths:

  • macOS: ~/Library/Application Support/Sublime Text 3/Packages/User
  • Linux: ~/.config/sublime-text-3/Packages/User
  • Windows: %APPDATA%\Sublime Text 3\Packages\User

Add plugin

Inside the settings directory create a file optimizt.py with the following content:

import os
import sublime
import sublime_plugin

optimizt = "~/.nodenv/shims/optimizt"

class OptimiztCommand(sublime_plugin.WindowCommand):
  def run(self, paths=[], options=""):
    if len(paths) < 1:
      return

    safe_paths = ["\"" + i + "\"" for i in paths]
    shell_cmd = optimizt + " " + options + " " + " ".join(safe_paths)
    cwd = os.path.dirname(paths[0])

    self.window.run_command("exec", {
      "shell_cmd": shell_cmd,
      "working_dir": cwd
    })

Specify path to executable inside optimizt variable, this path can be obtained by running command -v optimizt (on *nix) or where optimizt (on Windows).

Integrate the plugin into the sidebar context menu

Inside the settings directory create a file Side Bar.sublime-menu with the following content:

[
    {
        "caption": "Optimizt",
        "children": [
          {
              "caption": "Optimize Images",
              "command": "optimizt",
              "args": {
                "paths": [],
                "options": "--verbose"
              }
          },
          {
              "caption": "Optimize Images (lossless)",
              "command": "optimizt",
              "args": {
                "paths": [],
                "options": "--lossless --verbose"
              }
          },
          {
              "caption": "Create WebP",
              "command": "optimizt",
              "args": {
                "paths": [],
                "options": "--webp --verbose"
              }
          },
          {
              "caption": "Create WebP (lossless)",
              "command": "optimizt",
              "args": {
                "paths": [],
                "options": "--webp --lossless --verbose"
              }
          }
        ]
    }
]

How to use

Run the tool through the context menu on a file or directory:

Workflow for GitHub Actions

Create optimizt.yml file in the .github/workflows directory of your repository.

Insert the following code into optimizt.yml:

name: optimizt

on:
  # Triggers the workflow on push events but only for the “main” branch
  # and only when there's JPEG/PNG in the commmit
  push:
    branches:
      - main
    paths:
      - "**.jpe?g"
      - "**.png"
  
  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

jobs:
  convert:
    runs-on: ubuntu-latest

    steps:
      # Install Node.js to avoid EACCESS errors upon install packages
      - uses: actions/setup-node@v2
        with:
          node-version: 14

      - name: Install Optimizt
        run: npm install --global @funboxteam/optimizt

      - uses: actions/checkout@v2
        with:
          persist-credentials: false # otherwise, the token used is the GITHUB_TOKEN, instead of your personal token
          fetch-depth: 0 # get all commits (only the last one fetched by default)

      - name: Run Optimizt
        run: optimizt --verbose --force --avif --webp .

      - name: Commit changes
        run: |
          git add -A
          git config --local user.email "[email protected]"
          git config --local user.name "github-actions[bot]"
          git diff --quiet && git diff --staged --quiet \
            || git commit -am "Create WebP & AVIF versions"

      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ github.ref }}

This workflow will find all JPEG and PNG files in pushed commits and add the AVIF and WebP versions via a new commit.

More examples you can find in the workflows directory.

Troubleshooting

“spawn guetzli ENOENT”, etc

Make sure that the ignore-scripts option is not active.

See #9.

“pkg-config: command not found”, “fatal error: 'png.h' file not found”, etc

Some operating systems may lack of required libraries and utils, so you need to install them.

Example (on macOS via Homebrew):

brew install pkg-config libpng

Docker

Pull by name

docker pull funbox/optimizt

Pull by name and version

docker pull funbox/optimizt:5.0.1

Build the image

If you want to manually build the Docker image, you need to:

  1. Clone this repo and cd into it.
  2. Run docker build -t funbox/optimizt ..

OR:

  • Run docker build -t funbox/optimizt https://github.com/funbox/optimizt.git, but keep in mind that the .dockerignore file will be ignored.

Run the container

Inside the container WORKDIR is set to /src, so by default all paths will be resolved relative to it.

Usage example:

docker run -v $(pwd):/src funbox/optimizt --webp image.png

Credits

Cute picture for the project was made by Igor Garybaldi.

Sponsored by FunBox

More Repositories

1

harold

Compares frontend project bundles
JavaScript
241
star
2

optimus

Command line arguments parser for Elixir
Elixir
177
star
3

smppex

✉️ SMPP 3.4 protocol and framework implementation in Elixir
Elixir
106
star
4

fitting

Library add improve test log for RSpec and WebMock, validate its according to API Blueprint and Open API, show the documentation coverage with log.
Ruby
46
star
5

beatrix

A tool to chop off useless fonts glyphs and convert TTF/OTF into WOFF & WOFF2
JavaScript
46
star
6

blueprinter

API Blueprint renderer to output documentation as an HTML page
JavaScript
35
star
7

talks

Архив с публичными выступлениями наших сотрудников
29
star
8

init-exporter

Utility for exporting services described by Procfile to init system
Go
28
star
9

phantom-lord

Handy API for Headless Chromium
JavaScript
27
star
10

chokecherry

Wrapper around lager logger which limits the volume of info messages irrespectively of the lager's backend
Erlang
26
star
11

diamonds

A pile of shiny typed JS helpers for everyday usage
TypeScript
21
star
12

smppsend

Command line tool for sending messages to SMSC through SMPP
Elixir
20
star
13

sidekiq-influxdb

Writes Sidekiq job execution metrics to InfluxDB
Ruby
18
star
14

webpack-dev-server-firewall

Prevents access to dev server from unknown IPs
TypeScript
17
star
15

shrine-webdav

Provides a simple WebDAV storage for Shrine
Ruby
17
star
16

chronos

One library to rule the time
TypeScript
17
star
17

plumbapius

Plugs and tools for validating HTTP requests and responses according to API Blueprint specs
Elixir
14
star
18

crafter

API Blueprint parser written in pure JavaScript
JavaScript
13
star
19

languagetool-node

CLI spell and grammar checker
JavaScript
13
star
20

esplanade

Validate requests and responses against API Blueprint specifications
Ruby
12
star
21

babel-plugin-typograf

Babel plugin for enhancing text punctuation and readability
JavaScript
11
star
22

tomograph

Convert API Blueprint, Swagger and OpenAPI to JSON Schema and search through it
Ruby
11
star
23

eslint-plugin-no-only-tests

Disallow the use of describe.only() and it.only()
JavaScript
10
star
24

markdown-lint

Markdown code style linter
JavaScript
10
star
25

scss-vars-loader

SCSS variables for BEM-blocks
JavaScript
9
star
26

scss-imports-loader

Global imports for SCSS files
JavaScript
8
star
27

eslint-config

ESLint rules that follow our style guide
JavaScript
8
star
28

vscode-apib-ls

API Blueprint language server
JavaScript
8
star
29

api-validator

A tool to validate server responses using API Blueprint documentation
JavaScript
7
star
30

free-port-finder

Tiny utility for checking ports availability
JavaScript
7
star
31

face_control

Comment on problems in added lines of pull requests in Atlassian Bitbucket Server (formerly Stash)
Ruby
7
star
32

frontend-tests-runner

A library for running Mocha tests in parallel
JavaScript
6
star
33

loggun

Приводит логи приложения к единому формату
Ruby
6
star
34

scss-lint-config

Config for Stylelint SCSS linting
JavaScript
6
star
35

stylelint-rules

A collection of SCSS rules missing in stylelint-scss
JavaScript
6
star
36

bacula_exporter

Bacula exporter for Prometheus
Go
5
star
37

pipeline-heavy-job-plugin

This plugin allows defining job weight for pipeline projects as HeavyJob Plugin does for freestyle projects.
Java
5
star
38

rebuild-in-progress-webpack-plugin

Creates the file indicator at the beginning of the build and deletes it at the end
JavaScript
5
star
39

statesman-diagram

Generates DOT representations of Statesman machines and runs dot to render them to PNGs
Ruby
5
star
40

fazio

A tool to find an npm dep somewhere on your filesystem
JavaScript
5
star
41

piper

Utility for log rotation for 12-factor apps
Go
5
star
42

api-blueprint-tutorial

General information about API Blueprint tools in FunBox
JavaScript
5
star
43

eleb128

LEB128 Erlang implementation
Erlang
4
star
44

simplecov-bitbucket-server

Uploads test coverage data to Bitbucket Server via Code Coverage plugin
Ruby
4
star
45

activerecord-overflow_signalizer

Signalize when some primary key overflow soon
Ruby
4
star
46

dkrpm

Dockerized RPM building process powered by RPMBuilder
Shell
2
star
47

airborne_report

Generate reports on tests with the airborne gem
Ruby
2
star
48

qa-test

Тестовое задание для QA
Ruby
2
star
49

dioxy

Aggregating proxy for MQTT broker metrics in JSON format
Go
1
star
50

api-blueprint

API Blueprint specification
1
star
51

capistrano-init-exporter

Capistrano bindings for the init-exporter utility
Ruby
1
star
52

scss-utils

A small set of SCSS mixins
SCSS
1
star