Images

suggest change

Ruby's standard library has no image support, so image work goes through gems:

This article covers:

All examples were run with Ruby 4.0, chunky_png 1.4.0, ruby-vips 2.3.0, image_processing 2.2.0 and libvips 8.18.

Reading image size without a library

PNG and JPEG store their dimensions near the start of the file, so you can read them without decoding any pixels. This is a good exercise in binary data parsing:

PNG_SIGNATURE = "\x89PNG\r\n\x1A\n".b

def image_size(path)
  File.open(path, 'rb') do |f|
    head = f.read(24)
    if head.start_with?(PNG_SIGNATURE)
      # 8-byte signature, 4-byte chunk length, "IHDR", then width and height
      width, height = head.unpack('@16N2')
      return [:png, width, height]
    end
    return nil unless head.start_with?("\xFF\xD8".b)

    # JPEG: walk the segments until a Start Of Frame marker
    f.seek(2)
    loop do
      marker, length = f.read(4).unpack('xCn')   # skip 0xFF, read marker and length
      if (0xC0..0xCF).cover?(marker) && ![0xC4, 0xC8, 0xCC].include?(marker)
        height, width = f.read(5).unpack('xn2')   # skip precision byte
        return [:jpeg, width, height]
      end
      f.seek(length - 2, IO::SEEK_CUR)
    end
  end
end

p image_size('photo.png')
p image_size('photo.jpg')
p image_size('drawing.png')
p image_size(__FILE__)
[:png, 1200, 800]
[:jpeg, 1200, 800]
[:png, 200, 100]
nil

In real code use a library: libvips (shown below) reads only the header when you open a file, and the fastimage gem does the same for many formats, including over HTTP.

chunky_png: pixels in pure Ruby

$ gem install chunky_png

Creating and drawing

ChunkyPNG::Image.new(width, height, background) creates a canvas. image[x, y] = color sets a pixel, and there are helpers for lines, rectangles and circles:

require 'chunky_png'

# 200x100 image filled with white
png = ChunkyPNG::Image.new(200, 100, ChunkyPNG::Color::WHITE)

# Horizontal gradient from blue to red in the top half
(0...200).each do |x|
  t = x / 199.0
  color = ChunkyPNG::Color.rgb((255 * t).round, 0, (255 * (1 - t)).round)
  (0...50).each { |y| png[x, y] = color }
end

# Shapes in the bottom half: stroke color, then fill color
png.rect(10, 60, 60, 90, ChunkyPNG::Color.rgb(0, 128, 0), ChunkyPNG::Color.from_hex('#90ee90'))
png.circle(120, 75, 15, ChunkyPNG::Color::BLACK, ChunkyPNG::Color.rgba(255, 165, 0, 200))
png.line(150, 60, 190, 90, ChunkyPNG::Color.html_color(:purple))

png.save('drawing.png', :best_compression)
puts File.size('drawing.png')
1095

Reading pixels

A color in chunky_png is a plain Integer laid out as 0xRRGGBBAA. The ChunkyPNG::Color module has functions to build colors and take them apart:

require 'chunky_png'

png = ChunkyPNG::Image.from_file('drawing.png')
puts "#{png.width}x#{png.height}"

c = png[0, 0]
p c                                   # a color is just an Integer: 0xRRGGBBAA
puts ChunkyPNG::Color.to_hex(c)
p ChunkyPNG::Color.to_truecolor_alpha_bytes(png[199, 0])
puts ChunkyPNG::Color.r(png[100, 10]), ChunkyPNG::Color.b(png[100, 10])
puts ChunkyPNG::Color.to_hex(png[120, 75])   # orange blended onto white
200x100
65535
#0000ffff
[255, 0, 0, 255]
128
127
#ffb837ff

The last pixel shows that drawing a semi-transparent color blends it with what's already there.

Transforming

Transform methods return a new image. The versions ending in ! change the image in place:

require 'chunky_png'

png = ChunkyPNG::Image.from_file('drawing.png')

top    = png.crop(0, 0, 200, 50)          # x, y, width, height
small  = png.resample_bilinear(100, 50)   # or resample_nearest_neighbor
turned = png.rotate_right                 # 90 degrees clockwise
mirror = png.flip_vertically              # also: mirror (left-right), rotate_180

[top, small, turned, mirror].each { |img| puts "#{img.width}x#{img.height}" }

gray = png.dup
gray.grayscale!
puts ChunkyPNG::Color.to_hex(gray[0, 0])

# Per-pixel processing: invert colors, keep alpha
inverted = ChunkyPNG::Image.new(png.width, png.height)
png.height.times do |y|
  png.width.times do |x|
    c = png[x, y]
    inverted[x, y] = ChunkyPNG::Color.rgba(255 - ChunkyPNG::Color.r(c),
                                           255 - ChunkyPNG::Color.g(c),
                                           255 - ChunkyPNG::Color.b(c),
                                           ChunkyPNG::Color.a(c))
  end
end
puts ChunkyPNG::Color.to_hex(inverted[0, 0])

# Encode to a binary String instead of a file
blob = small.to_blob
p blob.encoding, blob.bytesize, blob[0, 8]
again = ChunkyPNG::Image.from_blob(blob)
puts "#{again.width}x#{again.height}"
200x50
100x50
100x200
200x100
#1c1c1cff
#ffff00ff
#<Encoding:BINARY (ASCII-8BIT)>
930
"\x89PNG\r\n\x1A\n"
100x50

chunky_png works well for small generated images: badges, sparklines, QR codes (the rqrcode gem uses it), test fixtures. Every pixel is a Ruby object operation, though, so it's slow on photos. Here is a downscale of a 1200x800 PNG to 300x200, then saving it:

require 'chunky_png'
require 'vips'

def measure(label)
  t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  yield
  puts format('%-11s %6.1f ms', label, (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t) * 1000)
end

measure('chunky_png') do
  png = ChunkyPNG::Image.from_file('photo.png')
  png.resample_bilinear!(300, 200)
  png.save('bench-chunky.png')
end
measure('vips') do
  Vips::Image.thumbnail('photo.png', 300).write_to_file('bench-vips.png')
end
chunky_png   342.1 ms
vips          20.4 ms

ruby-vips

Installing

ruby-vips loads the libvips shared library at runtime through FFI, so you need both the gem and the library:

$ gem install ruby-vips image_processing
$ brew install vips                 # macOS
$ sudo apt install libvips42        # Debian / Ubuntu

On Windows, download vips-dev-x64-all-<version>.zip from the libvips releases, unzip it, and point RUBY_DLL_PATH at its bin directory (RubyInstaller ignores PATH when it looks for a DLL's dependencies):

> set RUBY_DLL_PATH=C:\tools\vips-dev-8.18\bin
> ruby -rvips -e "puts Vips.version_string"
8.18.7

How libvips works

libvips images are immutable. Every operation returns a new Vips::Image describing a computation, and no pixels are processed until you write the result or ask for a value. libvips then streams the image through the whole pipeline in small tiles on all CPU cores, so even huge images need little memory.

Creating a test image

This builds the 1200x800 photo.jpg used in the rest of the article: a color gradient made with pixel arithmetic, plus a text label:

require 'vips'

# A 1200x800 RGB gradient: red grows left to right, green top to bottom
xy    = Vips::Image.xyz(1200, 800)          # 2 bands: the x and y of each pixel
red   = xy[0] * (255.0 / 1199)
green = xy[1] * (255.0 / 799)
blue  = Vips::Image.black(1200, 800) + 128
photo = red.bandjoin([green, blue]).cast(:uchar).copy(interpretation: :srgb)

# Black text on a white box in the top-left corner
text  = Vips::Image.text('Ruby + libvips', dpi: 300, font: 'sans bold')  # 1-band mask
photo = photo.draw_rect([255, 255, 255], 40, 40, text.width + 40, text.height + 40, fill: true)
area  = photo.crop(60, 60, text.width, text.height)
label = text.ifthenelse([0, 0, 0], area, blend: true)   # mask picks text color or background
photo = photo.insert(label, 60, 60)

photo.write_to_file('photo.jpg', Q: 90)
photo.write_to_file('photo.png')
puts "#{photo.width}x#{photo.height}, #{photo.bands} bands, #{photo.format}"
puts File.size('photo.jpg'), File.size('photo.png')
1200x800, 3 bands, uchar
72980
126496

Arithmetic operators work on whole images: xy[0] * 0.2 multiplies every pixel of band 0. A band is a channel: 1 for grayscale, 3 for RGB, 4 for RGB with alpha. format is the type of each value (:uchar is 0..255) and interpretation says how to read the bands (:srgb, :b_w, :cmyk, ...).

Loading and metadata

require 'vips'

image = Vips::Image.new_from_file('photo.jpg')
puts "#{image.width}x#{image.height}"
puts image.bands, image.format, image.interpretation
puts image.get('vips-loader')
p image.get_fields.first(8)
p image.has_alpha?

# Only the header is read so far; pixels are decoded when an output needs them
avg = image.avg
puts avg.round(2)
p image.getpoint(0, 0), image.getpoint(1199, 799)
1200x800
3
uchar
srgb
jpegload
["width", "height", "bands", "format", "coding", "interpretation", "xoffset", "yoffset"]
false
133.16
[1.0, 0.0, 128.0]
[255.0, 254.0, 128.0]

getpoint returns the band values of one pixel as floats. The 1.0 instead of 0.0 comes from JPEG compression.

Resizing, cropping and rotating

For thumbnails use Vips::Image.thumbnail. It opens the file itself, so it can decode a JPEG at reduced size (shrink-on-load), it applies EXIF rotation, and it handles color profiles. It's much faster than opening the image and calling resize:

require 'vips'

# thumbnail opens the file itself and can shrink while decoding (fast for JPEG)
thumb = Vips::Image.thumbnail('photo.jpg', 300)
puts "thumbnail: #{thumb.width}x#{thumb.height}"

square = Vips::Image.thumbnail('photo.jpg', 200, height: 200, crop: :centre)
puts "square:    #{square.width}x#{square.height}"

# Fit inside a 4000x400 box but never enlarge
box = Vips::Image.thumbnail('photo.png', 4000, height: 400, size: :down)
puts "box:       #{box.width}x#{box.height}"

image = Vips::Image.new_from_file('photo.jpg')
half    = image.resize(0.5)                       # scale factor
stretch = image.resize(0.5, vscale: 0.25)         # different vertical scale
part    = image.crop(100, 200, 300, 150)          # left, top, width, height
rotated = image.rot(:d90)                         # also :d180, :d270
tilted  = image.rotate(15, background: [255, 255, 255])  # any angle, canvas grows
flipped = image.flip(:horizontal)
padded  = image.embed(20, 20, image.width + 40, image.height + 40,
                      extend: :background, background: [255, 255, 255])

{ half:, stretch:, part:, rotated:, tilted:, flipped:, padded: }.each do |name, img|
  puts format('%-8s %dx%d', "#{name}:", img.width, img.height)
end
thumbnail: 300x200
square:    200x200
box:       600x400
half:    600x400
stretch: 600x200
part:    300x150
rotated: 800x1200
tilted:  1366x1083
flipped: 1200x800
padded:  1240x840

With a single size, thumbnail fits the width and keeps the aspect ratio. crop: :centre fills the box exactly and cuts off the overflow; crop: :attention looks for the most interesting region (skin tones, saturated colors, edges) instead. For an image already in memory, use image.thumbnail_image(300), which can't do shrink-on-load.

Saving and converting formats

The file extension picks the saver, and saver options are keyword arguments:

require 'vips'

image = Vips::Image.new_from_file('photo.png')

image.write_to_file('out.jpg', Q: 80, interlace: true)        # progressive JPEG
image.write_to_file('out.webp', Q: 75)
image.write_to_file('out-lossless.webp', lossless: true)
image.write_to_file('out.avif', Q: 50, effort: 4)
image.write_to_file('out.png', compression: 9)
image.write_to_file('out-8bit.png', palette: true, dither: 0)  # 256 colors, like pngquant

Dir['out*'].sort.each { |f| puts format('%-18s %7d bytes', f, File.size(f)) }

# Options can also go in the file name
image.write_to_file('small.jpg[Q=60,keep=none]')
puts File.size('small.jpg')
out-8bit.png         12865 bytes
out-lossless.webp     3936 bytes
out.avif              5034 bytes
out.jpg              27631 bytes
out.png             123920 bytes
out.webp              9056 bytes
23003

A smooth gradient compresses unusually well as WebP and AVIF, and it shows banding when reduced to 256 colors. Real photos give different numbers, so measure with your own images. keep: :none (libvips 8.15+, it replaces the old strip: true) drops EXIF, XMP and ICC metadata.

Working with strings and raw pixels

Uploads and HTTP responses arrive as binary strings. new_from_buffer and write_to_buffer work in memory, without temporary files:

require 'vips'

bytes = File.binread('photo.jpg')       # e.g. an upload or an HTTP response body

image = Vips::Image.new_from_buffer(bytes, '')    # format is detected from the bytes
puts image.get('vips-loader')

webp = image.thumbnail_image(400).write_to_buffer('.webp', Q: 70)
p webp.encoding, webp.bytesize, webp[0, 4], webp[8, 4]

# Raw pixels: one byte per band, row by row
tiny = image.resize(4.0 / 1200)                   # 4x3 pixels
raw = tiny.write_to_memory
p raw.bytesize                                    # 4 * 3 * 3 bands
p raw.unpack('C*').each_slice(3).first(2)
p tiny.to_a[0][0]                                 # nested arrays: rows, pixels, bands

# And back: build an image from raw bytes
pixels = [255, 0, 0,  0, 255, 0,  0, 0, 255,  255, 255, 255].pack('C*')
strip = Vips::Image.new_from_memory(pixels, 4, 1, 3, :uchar)
p strip.getpoint(1, 0)
jpegload_buffer
#<Encoding:BINARY (ASCII-8BIT)>
2518
"RIFF"
"WEBP"
36
[[97, 106, 161], [128, 80, 149]]
[97, 106, 161]
[0.0, 255.0, 0.0]

The second argument to new_from_buffer is a string of loader options, such as "fail_on=error". write_to_memory and new_from_memory let you exchange pixels with other libraries. To convert a chunky_png image, pass png.to_blob to new_from_buffer.

EXIF orientation and metadata

Phones often store pixels sideways and set an EXIF orientation tag. autorot applies it (thumbnail does so automatically). Strip metadata before publishing user photos, because EXIF can include GPS coordinates:

require 'vips'

# Simulate a phone photo: pixels stored sideways plus EXIF tags
photo = Vips::Image.new_from_file('photo.jpg').rot(:d270)
tagged = photo.mutate do |m|
  m.set_type!(GObject::GINT_TYPE, 'orientation', 6)          # "rotate 90 CW to display"
  m.set_type!(GObject::GSTR_TYPE, 'exif-ifd0-Artist', 'Jane Doe')
end
tagged.write_to_file('phone.jpg')

image = Vips::Image.new_from_file('phone.jpg')
puts "stored:      #{image.width}x#{image.height}"
puts "orientation: #{image.get('orientation')}"
puts "artist:      #{image.get('exif-ifd0-Artist')}"
p image.get_fields.grep(/exif/).first(4)

upright = image.autorot                      # rotate by EXIF orientation
puts "upright:     #{upright.width}x#{upright.height}"

# Strip metadata (EXIF, XMP, GPS, ...) before publishing user uploads
upright.write_to_file('clean.jpg', keep: :none)
clean = Vips::Image.new_from_file('clean.jpg')
p clean.get_fields.grep(/exif|orientation/)
stored:      800x1200
orientation: 6
artist:      Jane Doe (Jane Doe, ASCII, 9 components, 9 bytes)
["exif-data", "exif-ifd0-Orientation", "exif-ifd0-XResolution", "exif-ifd0-YResolution"]
upright:     1200x800
[]

Images are immutable, so metadata is changed inside a mutate block, which works on a private copy.

Filters and color

require 'vips'

image = Vips::Image.new_from_file('photo.jpg')

gray     = image.colourspace(:b_w)                  # 1 band
blurred  = image.gaussblur(4)                       # sigma in pixels
sharp    = image.sharpen(sigma: 1.0)
brighter = (image * 1.2 + 10).cast(:uchar)          # arithmetic on every pixel
inverted = image.invert
sepia    = image.recomb(Vips::Image.new_from_array([[0.393, 0.769, 0.189],
                                                    [0.349, 0.686, 0.168],
                                                    [0.272, 0.534, 0.131]])).cast(:uchar)

{ gray:, blurred:, sharp:, brighter:, inverted:, sepia: }.each do |name, img|
  px = img.getpoint(600, 400).map(&:round)
  puts format('%-9s bands=%d  center=%p', name, img.bands, px)
end
gray      bands=1  center=[128]
blurred   bands=3  center=[128, 128, 129]
sharp     bands=3  center=[126, 128, 127]
brighter  bands=3  center=[161, 163, 162]
inverted  bands=3  center=[129, 127, 128]
sepia     bands=3  center=[171, 153, 119]

Arithmetic produces float pixels. cast(:uchar) converts them back to 0..255 and clips values that are out of range. recomb multiplies each pixel's bands by a matrix, which covers sepia, channel swaps and custom grayscale weights.

Watermarks and compositing

composite blends an image with an alpha channel on top of another. insert pastes pixels without blending:

require 'vips'

def watermark(image, label, opacity: 0.5, margin: 20)
  mask = Vips::Image.text(label, dpi: 150, font: 'sans bold')    # 0..255 coverage
  # A white RGBA image whose alpha is the text mask scaled by opacity
  overlay = mask.new_from_image([255, 255, 255])
                .copy(interpretation: :srgb)
                .bandjoin((mask * opacity).cast(:uchar))
  image.composite(overlay, :over,
                  x: image.width - overlay.width - margin,
                  y: image.height - overlay.height - margin)
end

image = Vips::Image.new_from_file('photo.jpg')
marked = watermark(image, '(c) example.com')
puts "#{marked.width}x#{marked.height}, bands=#{marked.bands}"
marked = marked.flatten if marked.has_alpha?           # JPEG has no alpha channel
marked.write_to_file('marked.jpg')

# Paste one image onto another: a framed thumbnail in the top-right corner
thumb = Vips::Image.thumbnail('photo.jpg', 240)
framed = thumb.embed(4, 4, thumb.width + 8, thumb.height + 8, extend: :white)
combined = image.insert(framed, image.width - framed.width - 20, 20)
combined.write_to_file('combined.jpg')
puts "#{combined.width}x#{combined.height}"
1200x800, bands=4
1200x800

new_from_image([255, 255, 255]) makes an image the same size as mask with every pixel set to that constant. composite always returns an image with alpha, so flatten it (optionally with background: [r, g, b]) before saving to a format without transparency.

image_processing: thumbnail pipelines

image_processing wraps ruby-vips in a chainable, reusable pipeline with the resize modes web apps need:

require 'image_processing/vips'

pipeline = ImageProcessing::Vips.source('photo.jpg')

# call without destination writes to a Tempfile and returns it
file = pipeline.resize_to_limit(400, 400).call
p file.class, File.extname(file.path)
puts Vips::Image.new_from_file(file.path).then { "#{it.width}x#{it.height}" }

pipeline.resize_to_fill(300, 300, crop: :attention)
        .convert('webp')
        .saver(quality: 80)
        .call(destination: 'avatar.webp')

pipeline.resize_and_pad(500, 500, background: [255, 255, 255])
        .call(destination: 'padded.png')

pipeline.resize_to_fit(200, nil)
        .rotate(90)
        .colourspace(:b_w)            # unknown methods are forwarded to Vips::Image
        .call(destination: 'gray.jpg')

%w[avatar.webp padded.png gray.jpg].each do |f|
  img = Vips::Image.new_from_file(f)
  puts format('%-12s %dx%d bands=%d', f, img.width, img.height, img.bands)
end
Tempfile
".jpg"
400x267
avatar.webp  300x300 bands=3
padded.png   500x500 bands=3
gray.jpg     133x200 bands=1

The resize methods:

Method Result
resize_to_limit(w, h) fits inside wxh, only ever shrinks
resize_to_fit(w, h) fits inside wxh, may enlarge
resize_to_fill(w, h) exactly wxh, crops the overflow
resize_and_pad(w, h) exactly wxh, pads with background
crop(left, top, w, h) a region of the image

Pass nil for one dimension to constrain only the other. Pipelines are immutable values, so one base pipeline can produce many outputs. apply takes a hash of operations, which suits variants defined in configuration:

require 'image_processing/vips'

VARIANTS = {
  small:  { resize_to_fill: [150, 150] },
  medium: { resize_to_limit: [600, 600] },
  large:  { resize_to_limit: [1600, 1600] },
}.freeze

def make_variants(path, out_dir)
  source = ImageProcessing::Vips.source(path).convert('webp').saver(quality: 80)
  VARIANTS.to_h do |name, ops|
    dest = File.join(out_dir, "#{File.basename(path, '.*')}-#{name}.webp")
    source.apply(ops).call(destination: dest)
    [name, dest]
  end
end

Dir.mkdir('variants') unless Dir.exist?('variants')
make_variants('photo.jpg', 'variants').each do |name, dest|
  img = Vips::Image.new_from_file(dest)
  puts format('%-7s %-28s %4dx%-4d %6d bytes', name, dest, img.width, img.height, File.size(dest))
end
small   variants/photo-small.webp     150x150    1110 bytes
medium  variants/photo-medium.webp    600x400    4614 bytes
large   variants/photo-large.webp    1200x800   11648 bytes

The large variant stays at 1200x800 because resize_to_limit never enlarges. call without destination: returns a Tempfile, which is convenient for uploading the result to S3.

Handling untrusted images

Image decoders are a common attack surface, and a small file can claim enormous dimensions (a "decompression bomb"). When processing uploads:

require 'vips'

Vips.block_untrusted(true)    # disable loaders not meant for hostile input (SVG, PDF, ImageMagick, ...)
MAX_PIXELS = 40_000_000
ALLOWED    = %w[jpegload_buffer pngload_buffer webpload_buffer heifload_buffer gifload_buffer]

class BadImage < StandardError; end

def upload_thumbnail(bytes, size = 300)
  header = Vips::Image.new_from_buffer(bytes, '')          # reads only the header
  loader = header.get('vips-loader')
  raise BadImage, "format not allowed: #{loader}" unless ALLOWED.include?(loader)
  if header.width * header.height > MAX_PIXELS
    raise BadImage, "too many pixels: #{header.width}x#{header.height}"
  end

  # Decode for real; fail_on=error (a loader option) turns corrupt data into an exception
  Vips::Image.thumbnail_buffer(bytes, size, option_string: "fail_on=error").write_to_buffer('.jpg', Q: 85)
rescue Vips::Error => e
  raise BadImage, e.message.lines.first.strip
end

def try(label)
  jpeg = upload_thumbnail(yield)
  puts "#{label}: ok, #{jpeg.bytesize} byte thumbnail"
rescue BadImage => e
  puts "#{label}: rejected (#{e.message})"
end

try('photo')     { File.binread('photo.jpg') }
try('text')      { 'definitely not an image' }
try('svg')       { '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>' }
try('huge')      { Vips::Image.black(10_000, 5_000).write_to_buffer('.png') }
try('truncated') { File.binread('photo.jpg')[0, 20_000] }
photo: ok, 5719 byte thumbnail
text: rejected (VipsForeignLoad: buffer is not in a known format)
svg: rejected (VipsForeignLoad: buffer is not in a known format)
huge: rejected (too many pixels: 10000x5000)
truncated: rejected (VipsJpeg: premature end of JPEG image)

Without block_untrusted the SVG would load with svgload_buffer. libvips also prints warnings such as VIPS-WARNING **: error in tile to stderr while it decodes damaged files. They don't affect the result.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents