71

I'm searching best tool to compress images (png and jpeg) via command line.
After googling I found trimage which is good as it compresses both png and jepeg, but compression ratio is very poor in this case.

I came across jpeg-optimizer.com online tool which does the job way better than trimage. Can any one help to find the right tool for this.

Mukesh Yadav
  • 2,256
  • 2
  • 33
  • 51

3 Answers3

49

I'm using the following tools to perform lossless image compression:

For each of the programs, I've created two shortcuts:

  1. One that does the actual compression, and shows the file size of both files
  2. One that replaces the original file with the compressed one (If I'm satisfied, I'll do arrow-up, prefix my previous command with a "m", and press enter).

I've put this in my .bashrc:

# Image optimization tools
png() {
    pngcrush -brute "$1"{,.} && du -b "$1"{,.}
}
gif() {
    gifsicle -O "$1" -o "$1." && du -b "$1"{,.}
}
jpeg() {
    jpegtran "$1" > "$1." && du -b "$1"{,.}
}
# Just for easy access in history
mpng() {
    mv "$1"{.,}
}
mgif() {
    newsize=$(wc -c <"$1.")
    oldsize=$(wc -c <"$1")
    if [ $oldsize -gt $newsize ] ; then
        mv "$1"{.,}
    else
        rm "$1."
    fi  
}
mjpeg() {
    mv "$1"{.,}
}

Note: pngcrush -brute is very verbose. Redirect the output to /dev/null if you're not interested in the progress.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    gifsicle only started optimising with the `-O3` flag in a new release (not available on `apt` currently) - see [release 1.82.1](https://github.com/pornel/giflossy/releases) (replace your `/usr/bin/gifsicle` binary the appropriate one). My notes on gif optimisation with it are [here](https://github.com/lmmx/devnotes/wiki/Gif-terminal-manipulation) – Louis Maddox Jul 29 '15 at 17:31
  • 1
    Your `jpegtran` command seems to do nothing at all, it results in a file of the exact same size. Why do you have no options specified? – pretzlstyle Feb 28 '17 at 06:24
  • @jphollowed `jpegtran` optimizes by default. If the file does not change, then jpegtran cannot reduce the size in a lossless way. – Rob W Feb 28 '17 at 07:29
  • I like pngcrush because of lossless compression. I just copy the png files to a temp diretory. Then I run a batch file in Windows that processes all the PNG in the current directory. `for /R %cd% %%f in (*.png) do ( pngcrush -reduce -brute -ow "%%~nf.png" "temp%%~nf.png" )` Then I run a folder comparison program to review the two folders and visually files are identical but I copy over the smaller optimized files to the source directory. – Sun Sep 26 '17 at 22:09
38
Kornel
  • 97,764
  • 37
  • 219
  • 309
17

If you are on Linux, try mogrify tool from the imagemagick suite

It is quite handy on command line.

Ex :

mogrify -resize 50% rose.jpg

mogrify -format jpg *.png
old-ufo
  • 2,799
  • 2
  • 28
  • 40
Udantha
  • 300
  • 3
  • 6