Convert a file with binary 16 values to a range

Similar by following command with ImageMagick

convert -contrast-stretch 0x512 -size 240x180 -depth 16 gray:REC003-00247.dpt test6.bmp

A small ruby program that tries to the same


#!/usr/bin/ruby

# Scale value w in range between [min, max] to new range [0, nmax]
def to_range(min, max, nmax, w)
  scale = nmax.to_f / (max-min).to_f  # scaling factor
  wl = [[w, min].max, max].min        # truncate values outside of range
  ((wl - min).to_f * scale).to_i      # move and scale value
end

data = IO.binread("test.bmp").bytes
# convert bytes to 16 words (significant byte first)
words = (0...(data.size / 2)).collect { |i| (data[i] << 8) | data[i+1] }
# map words to range
ranged = words.map { |w| to_range(0x6000, 0x8000, 0xffff, w) }
# convert words to bytes
data2 = ranged.collect { |w| [ w >> 8, w & 0xff ] }.flatten
# store file
IO.binwrite("test-conv.bmp", data2.pack('C*'))