All formats

MiniMagick

LanguageRuby
LicenseMIT (ImageMagick: ImageMagick License)
Repositorygithub.com/minimagick/minimagick
DocumentationREADME, API docs
Depends onImageMagick 7 (magick) or 6 (convert, identify) installed on the system
Read / writeyes / yes; all ImageMagick JPEG options; Exif reading

MiniMagick builds ImageMagick command lines and runs them. MiniMagick::Image methods map to ImageMagick options (resize, quality, interlace, strip), so anything in the ImageMagick documentation works. Because the work happens in a separate process, Ruby memory stays small, but each call has process start-up cost and ImageMagick loads the full image.

MiniMagick::Image.open copies the file to a temporary file and changes the copy; MiniMagick::Image.new changes the file in place.

Installation#

Shell
# Debian / Ubuntu
sudo apt install imagemagick
# macOS
brew install imagemagick
bundle add mini_magick

Basic usage: auto-orient, resize and save as JPEG#

Ruby
require "mini_magick"

image = MiniMagick::Image.open("photo.jpg")
puts "#{image.width} x #{image.height}, #{image.type}"

image.combine_options do |b|   # one magick command for all options
  b.auto_orient
  b.resize "1200x1200>"        # fit inside 1200x1200, only shrink
  b.quality 85
  b.interlace "Plane"          # progressive JPEG
end
image.write "out.jpg"

How to read Exif data#

Ruby
image = MiniMagick::Image.new("photo.jpg")   # no copy needed for reading
exif = image.exif                            # hash of Exif tags
puts exif["Model"]
puts exif["DateTimeOriginal"]
puts image["%[EXIF:Orientation]"]            # any ImageMagick format escape

How to get JPEG dimensions and quality#

Ruby
image = MiniMagick::Image.new("photo.jpg")
puts image.dimensions.inspect     # [4032, 3024]
puts image["%Q"]                  # estimated JPEG quality, e.g. "92"
puts image.data["properties"]["jpeg:sampling-factor"]   # "2x2,1x1,1x1" = 4:2:0

How to strip metadata and set chroma subsampling#

Ruby
MiniMagick.convert do |convert|
  convert << "photo.jpg"
  convert.strip                       # remove Exif, XMP, comments, ICC
  convert.sampling_factor "4:4:4"
  convert.quality 90
  convert << "clean.jpg"
end

How to convert PNG to JPEG with a white background#

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

Tips#