Thursday, February 7, 2013

Converting twips to pixels and vice-versa

Here is a Ruby program to convert between twips and pixels:

#!/bin/ruby

# As per PostScript definition
TWIPS_PER_INCH = 1440

def twips_to_pixels(twips, dpi, round = true)
  raise "Invalid DPI" if (dpi <= 0)
  raise "Invalid twips" if (twips < 0)

  num_pixels = ((twips / TWIPS_PER_INCH.to_f) * dpi)
  return round ? num_pixels.round : num_pixels.floor
end

def pixels_to_twips(pixels, dpi, round = true)
  raise "Invalid DPI" if (dpi <= 0)
  raise "Invalid number of pixels" if (pixels < 0)

  twips = ((pixels / dpi.to_f) * TWIPS_PER_INCH)
  return round ? twips.round : twips.floor
end

def numeric?(str)
  Float(str) != nil rescue false
end

def print_usage_and_exit
  puts "Usage: #{$0} [-t twips | -p pixels] [-d dpi]"
  exit(1)
end

if __FILE__ == $0
  print_usage_and_exit if ARGV.length != 4

  dpi = nil
  twips = nil
  pixels = nil

  [0, 2].each do |option_index|
    option = ARGV[option_index]
    option_val = ARGV[option_index + 1]
    print_usage_and_exit unless (numeric?(option_val))

    case option
      when "-d" then dpi = option_val.to_f
      when "-t" then twips = option_val.to_f
      when "-p" then pixels = option_val.to_f
      else print_usage_and_exit
    end
  end

  print_usage_and_exit if ((pixels.nil? && twips.nil?) || dpi.nil?)
  res = twips.nil? ? pixels_to_twips(pixels, dpi) : twips_to_pixels(twips, dpi)
  puts res
end

No comments:

Post a Comment

Post a Comment