Skip to content

Image Converter — Ruby source

Convert images between PNG, JPEG and WebP entirely in your browser. Batch-friendly with quality control and a before/after size delta — nothing is uploaded.

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

# Image converter — Ruby port of the image-converter tool (ruby-vips).

require "vips"

# Decode -> (JPEG only) flatten alpha onto white -> save at quality.
# Quality is 1..100 here; the web tool's slider is 0..1 (x100).
def convert_image(src, dst, target, quality: 85)
  image = Vips::Image.new_from_file(src, access: :sequential)

  # JPEG has no alpha channel: flatten onto white, or transparent pixels
  # render black in the encoded file.
  image = image.flatten(background: [255, 255, 255]) if target == "jpeg"

  case target
  when "jpeg" then image.jpegsave(dst, Q: quality)
  when "webp" then image.webpsave(dst, Q: quality)
  when "png"  then image.pngsave(dst) # PNG is lossless: no quality knob
  else raise ArgumentError, "unsupported target: #{target}"
  end
rescue Vips::Error => e
  raise ArgumentError, "encode failed: #{e.message}"
end

if $PROGRAM_NAME == __FILE__
  convert_image(ARGV[0], ARGV[1], ARGV[2])
end

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 →