• Stars
    star
    1,518
  • Rank 30,867 (Top 0.7 %)
  • Language
    Ruby
  • License
    MIT License
  • Created almost 13 years ago
  • Updated 2 months ago

Reviews

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

Repository Details

Optimize images using multiple utilities

Gem Version Build Status Rubocop CodeQL Code Climate Code Climate Coverage Depfu Inch CI

image_optim

Command line tool and ruby interface to optimize (lossless compress, optionally lossy) jpeg, png, gif and svg images using external utilities:

Based on ImageOptim.app.

Documentation for latest gem version and master branch.

A test application with latest image_optim and image_optim_pack is available on render: https://iopack.onrender.com/.

Gem installation

gem install image_optim

You may also want to install image_optim_pack (see Binaries pack).

gem install image_optim_pack

Bundler

Add to your Gemfile:

gem 'image_optim'

With image_optim_pack:

gem 'image_optim'
gem 'image_optim_pack'

With version:

gem 'image_optim', '~> 0.31'

If you want to check latest changes:

gem 'image_optim', :git => 'git://github.com/toy/image_optim.git'

Docker

This gem is also be available as docker image containing most binaries:

docker run --rm ghcr.io/toy/image_optim --version # image_optim version
docker run --rm ghcr.io/toy/image_optim --info # image_optim info including bin versions
docker run --rm -v "$PWD":/here -w /here ghcr.io/toy/image_optim image-in-this-folder.jpg

See image_optim_pack repository for Dockerfile and instructions.

Binaries location

Simplest way for image_optim to locate binaries is to install them in common location present in PATH (see Binaries installation).

If you cannot install to common location, then install to custom one and add it to PATH.

Specify custom bin location using XXX_BIN environment variable (JPEGOPTIM_BIN, OPTIPNG_BIN, …).

Besides permanently setting environment variables in ~/.profile, ~/.bash_profile, ~/.bashrc, ~/.zshrc, … they can be set:

  • before command:

    PATH="/custom/location:$PATH" image_optim *.jpg

    for example:

    PATH="/Applications/ImageOptim.app/Contents/MacOS:$PATH" image_optim *.jpg

  • inside script:

    ENV['PATH'] = "/custom/location:#{ENV['PATH']}"; ImageOptim.optimize_images([…])

    for example:

    ENV['PATH'] = "/Applications/ImageOptim.app/Contents/MacOS:#{ENV['PATH']}"; ImageOptim.optimize_images([…])

Binaries installation

Binaries pack

Easiest way to get latest versions of most binaries for image_optim for Linux and Mac OS X is by installing image_optim_pack gem.

Check installation instructions in Gem installation section.

Pack doesn't include pngout and svgo binaries, their installation instructions are provided below.

Linux - Debian/Ubuntu

sudo apt-get install -y advancecomp gifsicle jhead jpegoptim libjpeg-progs optipng pngcrush pngquant

If you get an old version of pngquant, please check how to install up-to-date version or compile from source at http://pngquant.org/.

Linux - RHEL/Fedora/Centos

sudo yum install -y advancecomp gifsicle jhead libjpeg optipng pngquant

You may also need to install libjpeg-turbo-utils instead of libjpeg:

sudo yum install -y libjpeg-turbo-utils

You will also need to install jpegoptim and pngcrush from source:

jpegoptim

Replace X.Y.Z with latest version number from http://www.kokkonen.net/tjko/projects.html#jpegoptim.

JPEGOPTIM_VERSION=X.Y.Z
cd /tmp
curl -O http://www.kokkonen.net/tjko/src/jpegoptim-$JPEGOPTIM_VERSION.tar.gz
tar zxf jpegoptim-$JPEGOPTIM_VERSION.tar.gz
cd jpegoptim-$JPEGOPTIM_VERSION
./configure && make && make install

pngcrush

Replace X.Y.Z with latest version number from http://sourceforge.net/projects/pmt/files/pngcrush/.

PNGCRUSH_VERSION=X.Y.Z
cd /tmp
curl -O http://iweb.dl.sourceforge.net/project/pmt/pngcrush/$PNGCRUSH_VERSION/pngcrush-$PNGCRUSH_VERSION.tar.gz
tar zxf pngcrush-$PNGCRUSH_VERSION.tar.gz
cd pngcrush-$PNGCRUSH_VERSION
make && cp -f pngcrush /usr/local/bin

OS X: Macports

sudo port install advancecomp gifsicle jhead jpegoptim jpeg optipng pngcrush pngquant

OS X: Brew

brew install advancecomp gifsicle jhead jpegoptim jpeg optipng oxipng pngcrush pngquant jonof/kenutils/pngout

oxipng installation (optional)

Unless it is available in your chosen package manager, can be installed using cargo:

cargo install oxipng

pngout installation (optional)

If you installed the dependencies via brew, pngout should be installed already. Otherwise, you can install pngout by downloading and installing the binary versions.

Note: pngout is free to use even in commercial soft, but you can not redistribute, repackage or reuse it without consent and agreement of creator. license

svgo installation (optional)

svgo is available from NPM.

npm install -g svgo

If you prefer to install svgo to your project directory, use one of the following commands instead:

npm install svgo

yarn add svgo

When installing svgo to the project directory, you must add the following to your environment:

SVGO_BIN='node_modules/svgo/bin/svgo'

jpeg-recompress installation (optional)

Download and install the jpeg-recompress binary from the JPEG-Archive Releases page, or follow the instructions to build from source.

Usage

From shell

image_optim *.{jpg,png,gif,svg}

image_optim -r .

image_optim -h

From ruby

Initialize optimizer (or you can call optimization methods directly on ImageOptim):

image_optim = ImageOptim.new

image_optim = ImageOptim.new(:pngout => false)

image_optim = ImageOptim.new(:nice => 20)

Optimize image getting temp path:

image_optim.optimize_image('a.png')

Optimize image in place:

image_optim.optimize_image!('b.jpg')

Optimize image data:

image_optim.optimize_image_data(data)

Multiple images:

image_optim.optimize_images(Dir['*.png']) do |unoptimized, optimized|
  if optimized
    puts "#{unoptimized} => #{optimized}"
  end
end

image_optim.optimize_images!(Dir['*.*'])

image_optim.optimize_images_data(datas)

From rails

Rails image assets optimization is extracted into image_optim_rails gem.

Configuration

Configuration in YAML format will be read and prepended to options from two paths:

  • $XDG_CONFIG_HOME/image_optim.yml (by default ~/.config/image_optim.yml)
  • .image_optim.yml in current working directory

Paths can be changed using :config_paths option and --config-paths argument.

Example configuration:

nice: 20
pngout: false # disable
optipng:
  level: 5

Temporary directory

image_optim uses standard ruby library for creating temporary files. Temporary directory can be changed using one of TMPDIR, TMP or TEMP environment variables.

Options

  • :nice β€” Nice level, priority of all used tools with higher value meaning lower priority, in range -20..19, negative values can be set only if run by root user (defaults to 10)
  • :threads β€” Number of threads or disable (defaults to number of processors)
  • :verbose β€” Verbose output (defaults to false)
  • :pack β€” Require image_optim_pack or disable it, by default image_optim_pack will be used if available, will turn on :skip-missing-workers unless explicitly disabled (defaults to nil)
  • :skip_missing_workers β€” Skip workers with missing or problematic binaries (defaults to false)
  • :allow_lossy β€” Allow lossy workers and optimizations (defaults to false)
  • :cache_dir β€” Configure cache directory
  • :cache_worker_digests - Also cache worker digests along with original file digest and worker options: updating workers invalidates cache
  • :timeout β€” Maximum time in seconds to spend on one image, note multithreading and cache (defaults to unlimited)

Worker can be disabled by passing false instead of options hash or by setting option :disable to true.

advpng:

  • :level β€” Compression level: 0 - don't compress, 1 - fast, 2 - normal, 3 - extra, 4 - extreme (defaults to 4)

gifsicle:

  • :interlace β€” Interlace: true - interlace on, false - interlace off, nil - as is in original image (defaults to running two instances, one with interlace off and one with on)
  • :level β€” Compression level: 1 - light and fast, 2 - normal, 3 - heavy (slower) (defaults to 3)
  • :careful β€” Avoid bugs with some software (defaults to false)

jhead:

Worker has no options

jpegoptim:

  • :allow_lossy β€” Allow limiting maximum quality (defaults to false)
  • :strip β€” List of markers to strip: :com, :exif, :iptc, :icc, :xmp, :none or :all (defaults to :all)
  • :max_quality β€” Maximum image quality factor 0..100, ignored in default/lossless mode (defaults to 100)

jpegrecompress:

  • :allow_lossy β€” Allow worker, it is always lossy (defaults to false)
  • :quality β€” JPEG quality preset: 0 - low, 1 - medium, 2 - high, 3 - veryhigh (defaults to 3)
  • :method β€” Comparison Metric: mpe - Mean pixel error, ssim - Structural similarity, ms-ssim - Multi-scale structural similarity (slow!), smallfry - Linear-weighted BBCQ-like (may be patented) (defaults to ssim)

jpegtran:

  • :copy_chunks β€” Copy all chunks (defaults to false)
  • :progressive β€” Create progressive JPEG file (defaults to true)
  • :jpegrescan β€” Use jpegtran through jpegrescan, ignore progressive option (defaults to true)

optipng:

  • :level β€” Optimization level preset: 0 is least, 7 is best (defaults to 6)
  • :interlace β€” Interlace: true - interlace on, false - interlace off, nil - as is in original image (defaults to false)
  • :strip β€” Remove all auxiliary chunks (defaults to true)

oxipng:

  • :level β€” Optimization level preset: 0 is least, 6 is best (defaults to 3)
  • :interlace β€” Interlace: true - interlace on, false - interlace off, nil - as is in original image (defaults to false)
  • :strip β€” Remove all auxiliary chunks (defaults to true)

pngcrush:

  • :chunks β€” List of chunks to remove or :alla - all except tRNS/transparency or :allb - all except tRNS and gAMA/gamma (defaults to :alla)
  • :fix β€” Fix otherwise fatal conditions such as bad CRCs (defaults to false)
  • :brute β€” Brute force try all methods, very time-consuming and generally not worthwhile (defaults to false)
  • :blacken β€” Blacken fully transparent pixels (defaults to true)

pngout:

  • :copy_chunks β€” Copy optional chunks (defaults to false)
  • :strategy β€” Strategy: 0 - xtreme, 1 - intense, 2 - longest Match, 3 - huffman Only, 4 - uncompressed (defaults to 0)

pngquant:

  • :allow_lossy β€” Allow quality option (defaults to false)
  • :max_colors β€” Maximum number of colors to use (defaults to 256)
  • :quality β€” min..max - don't save below min, use less colors below max (both in range 0..100; in yaml - !ruby/range 0..100), ignored in default/lossless mode (defaults to 100..100, 0..100 in lossy mode)
  • :speed β€” speed/quality trade-off: 1 - slow, 3 - default, 11 - fast & rough (defaults to 3)

svgo:

  • :disable_plugins β€” List of plugins to disable (defaults to [])
  • :enable_plugins β€” List of plugins to enable (defaults to [])

Contributing

List of contributors to image_optim.

If you would like to contribute - that is great and you are very welcome. Please check few notes in file CONTRIBUTING.markdown.

ChangeLog

In separate file CHANGELOG.markdown.

Copyright

Copyright (c) 2012-2023 Ivan Kuchin. See LICENSE.txt for details.

More Repositories

1

blueutil

CLI for bluetooth on OSX: power, discoverable state, list, inquire devices, connect, info, …
Objective-C
999
star
2

dump

Rails app rake and capistrano tasks to create and restore dumps of database and assets
Ruby
89
star
3

image_size

measure image size using pure Ruby (by Keisuke Minami)
Ruby
85
star
4

image_optim_pack

Precompiled binaries for image_optim
Ruby
77
star
5

progress

Class to show progress during script run
Ruby
68
star
6

pHash

Ruby interface to pHash
Ruby
60
star
7

image_optim_rails

Optimize rails assets using image_optim
Ruby
55
star
8

in_threads

Run all possible enumerable methods in concurrent/parallel threads
Ruby
37
star
9

sdoc_all

sdoc_all is no longer maintained, try doc gem
Ruby
15
star
10

random_text

Class to make access to http://vesna.yandex.ru/ and http://lipsum.com/ easier
Ruby
10
star
11

output_compression

gzip compression output - it is just a mirror with applied patches
Ruby
9
star
12

rbenv-update-rubies

Update rbenv ruby versions
Shell
7
star
13

phamilie

Compute image fingerprints and similarity
Ruby
7
star
14

doc

Command line tool to get searchable documentation for ruby, rails, gems, plugins and other ruby related code in one place
Ruby
6
star
15

free_mem

Free memory on mac
C
6
star
16

fspath-mac

FSPath methods for mac
Objective-C
6
star
17

fspath

Better than Pathname
Ruby
5
star
18

tms

Time Machine Status
Ruby
5
star
19

upload_column

upload_column 0.2.1 with some fixes
Ruby
5
star
20

FinderPatch

Finder fixes: select next after trashing, label shortcuts, open in terminal, open in textmate
Objective-C
5
star
21

spec_routes_tester

Plugin with class that allows you much easier routes testing with rspec
Ruby
4
star
22

mate

TextMate project builder and TextMate 2 properties builder using git ignores for exclusions
Ruby
4
star
23

extended_form_helper

Helper methods to ease form creation
Ruby
4
star
24

cache_method

cache method result in attribute
Ruby
3
star
25

contacts

store a lot of contacts in one text field with validation and link creation
Ruby
3
star
26

data_columns

Store multiple columns in serialized data column
Ruby
3
star
27

rbenv-around-install

Run scripts before and after installing ruby using ruby-build
Shell
3
star
28

fspath-xattr

FSPath methods xattr and lxattr to work with extended attributes using ffi-xattr gem
Ruby
3
star
29

set_icon

set/unset custom icon for file
Objective-C
3
star
30

access

Plugin for writing allow/deny rules in controllers
Ruby
3
star
31

growler

Growl like messages in rails app
JavaScript
2
star
32

remove_stale_gems

remove unused gems
Ruby
2
star
33

toy.github.com

toy.github.com
JavaScript
2
star
34

toy

✨special✨ repository
2
star
35

TmCleanSave

TextMate bundle which removes extra whitespace and fixes tabs when saving file
C
2
star
36

russian

String methods to ease work with russian language
Ruby
2
star
37

ui

repository to easily distribute compiled ui reference
PHP
2
star
38

link.app

Create hardlink/symlink (alt to force symlink) for items selected in Finder
Objective-C
2
star
39

newTabHere.app

open new Terminal tab next to current with same dir
Objective-C
2
star
40

box-for-rubygems

Shell
1
star
41

restartable

Run code, Ctrl-C to restart, two Ctrl-C to stop
Ruby
1
star
42

rbenv-with

rbenv with 2.4
Shell
1
star
43

simple_scaffold

simple_scaffold
1
star
44

rb

repository to easily distribute compiled rb reference
JavaScript
1
star
45

Appscript

clone of Obj-C appscript
Objective-C
1
star
46

rake-gem-ghost

Help gem developers to test created gems β€” creates symlink from installed gem to current folder.
Ruby
1
star
47

TerminalPatch

New Terminal tab/window with same dir
Objective-C
1
star
48

SilverService

fork of application to make mac os x services from unix commands
Objective-C
1
star
49

mounter

As `diskutil mount` can't unlock APFS encrypted volumes the way it (most of the time) can Core Storage ones.
Swift
1
star
50

fix_html

helper to make html valid
Ruby
1
star
51

as

repository to easily distribute compiled actionscript reference
JavaScript
1
star
52

server_dotfiles

server dotfiles
1
star
53

xcode

Rake tasks to help packaging products made with Xcode.
Ruby
1
star
54

rails_seeder

Helpers to generate test data
Ruby
1
star
55

rb-appscript

because it still works even for ruby 3.0
Ruby
1
star