MiniMagick
| Language | Ruby |
|---|---|
| License | MIT |
| Repository | github.com/minimagick/minimagick |
| Documentation | README |
| Depends on | ImageMagick (magick or convert on PATH) and Ghostscript for PostScript |
| Read / write | yes (rasterized through Ghostscript) / yes (raster images wrapped in PostScript) |
MiniMagick builds ImageMagick command lines and runs them. It doesn’t load images into Ruby memory, so it’s light. For PostScript, ImageMagick calls Ghostscript to render pages to bitmaps; MiniMagick then works on those like any other image.
Rendering resolution is set by density before the input file. The default 72 dpi looks blurry: use 150-300. Output is raster: to keep PostScript vectors when converting to PDF, call Ghostscript with pdfwrite.
Installation#
Shell
gem install mini_magick
# plus ImageMagick and Ghostscript
sudo apt install imagemagick ghostscript # Debian / Ubuntu
brew install imagemagick ghostscript # macOS
Some Linux distributions disable PostScript in ImageMagick’s policy.xml (<policy domain="coder" rights="none" pattern="PS" />). Remove or relax that line if reading fails with “not authorized”.
Basic usage: render every page of a PostScript file to PNG#
Ruby
require "mini_magick"
MiniMagick.convert do |convert|
convert.density(150) # must come before the input
convert << "in.ps"
convert.background("white")
convert.alpha("remove")
convert << "page-%03d.png" # one file per page
end
How to render only the first page#
Ruby
require "mini_magick"
image = MiniMagick::Image.open("in.ps")
image.format("png", 0, { density: "300" }) # page 0, read at 300 dpi
image.write("page1.png")
How to get the page count and page size#
Ruby
image = MiniMagick::Image.open("in.ps")
puts image.pages.size # runs Ghostscript on the whole file
image.pages.each_with_index do |page, i|
puts "page #{i + 1}: #{page.width} x #{page.height} px at 72 dpi"
end
How to make a thumbnail of a PostScript file#
Ruby
MiniMagick.convert do |convert|
convert.density(72)
convert << "in.ps[0]" # [0] = first page only
convert.thumbnail("300x300")
convert.background("white")
convert.flatten
convert << "thumb.jpg"
end
How to save an image as PostScript#
Ruby
MiniMagick.convert do |convert|
convert << "photo.jpg"
convert << "ps3:photo.ps" # ps, ps2 or ps3 (compressed)
end
Tips#
MiniMagick.convertusesmagickon ImageMagick 7 andconverton ImageMagick 6.- PostScript from users runs as a program in Ghostscript. Limit the time with
MiniMagick.configure { |config| config.timeout = 30 }.