Skip to content

Image Resize & Watermark — Ruby source

Batch-resize images by width, height or percentage and stamp a text watermark with position, opacity and size control — entirely in your browser, nothing uploaded.

This is the Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.

# Image Resize & Watermark — Ruby (MiniMagick / ImageMagick) port of the image-resize-and-watermark tool.

require 'mini_magick'

# Mirrors the TS resizeAndWatermark: aspect-preserving resize (height is
# derived), then a bottom-right watermark — white text at 70% opacity over a
# dark stroke (the strokeText/fillText pair), then a WebP encode at 92%.
def resize_and_watermark(input, output, target_width, watermark)
  MiniMagick::Image.open(input) do |img|
    # "Wx" scales to width W with height auto — the round(h / w * W) behaviour.
    img.resize("#{target_width}x")

    w = img[:width].to_i
    h = img[:height].to_i
    font_size = (min(w, h) * 6 / 100.0).round # fontSize = min(w,h) * 6 / 100

    img.combine_options do |c|
      c.gravity('SouthEast')
      c.pointsize(font_size)
      c.font('DejaVu-Sans')              # ~ system-ui, sans-serif
      c.fill('rgba(255,255,255,0.7)')    # fillText: white at 70% alpha
      c.stroke('rgba(0,0,0,0.55)')       # strokeText: dark outline
      c.strokewidth([font_size / 14.0, 1].max) # lineWidth = max(1, fontSize/14)
      c.annotate('0x0+8+8', watermark)   # +8+8 = the 8 px bottom-right margin
    end

    img.format('webp', 92) # TS encodes image/webp at quality 0.92
    img.write(output)
  end
end

resize_and_watermark('input.jpg', 'output.webp', 1280, 'CosmoDev')

Also available in 8 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →