All formats

MiniMagick

LanguageRuby
LicenseMIT
Repositorygithub.com/minimagick/minimagick
DocumentationREADME, rubydoc.info
Depends onImageMagick 7 (or 6) command-line tools
Read / writeyes / yes, everything ImageMagick supports for PNG (bit depth, palette, text chunks)

MiniMagick builds ImageMagick commands (magick, identify, mogrify) and runs them as separate processes. It uses little memory in Ruby, because the image is never loaded into the Ruby process, and it supports every format and option ImageMagick has.

The cost is one process start per operation, which is slow when you run many small operations; batch them with combine_options or the MiniMagick.convert tool interface. For speed and memory, ruby-vips is faster. Since version 5 MiniMagick targets ImageMagick; GraphicsMagick works only partly.

Installation#

Shell
# ImageMagick first
sudo apt install imagemagick    # Debian / Ubuntu
brew install imagemagick        # macOS
# then
gem install mini_magick

Basic usage: open, resize and save a PNG#

Ruby
require "mini_magick"

image = MiniMagick::Image.open("in.png")   # works on a temporary copy
puts "#{image.width} x #{image.height}, #{image.type}"

image.resize "800x800>"   # fit inside 800x800, only shrink
image.write "out.png"

Image.open copies the file to a temporary file, so the original isn’t changed. MiniMagick::Image.new("in.png") edits the file in place.

How to get PNG width and height#

width, height and type run identify, which reads only the header:

Ruby
image = MiniMagick::Image.new("in.png")
puts image.dimensions.inspect   # [width, height]
puts image["%[colorspace] %[bit-depth]-bit"]   # any ImageMagick format escape

How to set PNG compression level and color type#

Ruby
image = MiniMagick::Image.open("in.png")
image.combine_options do |b|
  b.define "png:compression-level=9"
  b.define "png:color-type=3"   # 3 = palette; 2 = RGB; 6 = RGBA
  b.strip                       # remove metadata chunks
end
image.write "small.png"

How to convert PNG to JPEG#

Ruby
image = MiniMagick::Image.open("in.png")
image.combine_options do |b|
  b.background "white"
  b.flatten
  b.quality 85
end
image.format "jpg"
image.write "out.jpg"

How to read PNG text chunks#

ImageMagick reads tEXt, zTXt and iTXt chunks as image properties; data returns them from ImageMagick’s JSON output:

Ruby
image = MiniMagick::Image.open("in.png")
image.data["properties"].each { |key, value| puts "#{key}: #{value}" }

How to run a magick command directly#

The tool interface skips the temporary copy and runs one command:

Ruby
MiniMagick.convert do |convert|
  convert << "in.png"
  convert.resize "50%"
  convert.define "png:compression-level=9"
  convert << "out.png"
end

Tips#