Skip to content

Importing BMP images

wvanbergen edited this page Feb 25, 2011 · 1 revision

The following code snippet will load a BMP image from a file or IO stream. Use at your own risk.

require 'rubygems'
require 'chunky_png'

# get the data
data = StringIO.new(File.read('filename.bmp'))

bmp_file_header = data.read(14).unpack('a2VxxV')
bmp_info_header = data.read(40).unpack('V3v2V6')

raise "Not a BMP file"                  unless bmp_file_header[0] == "BM"
raise "Only 24-bit BMP files supported" unless bmp_info_header[4] == 24
raise "Compression not supported"       unless bmp_info_header[5] == 0

width  = bmp_info_header[1]
height = bmp_info_header[2]
line_remainder = 4 - (width * 3) % 4

pixels = []
1.upto(height) do |i|
  bytes = data.read(width * 3 + line_remainder).unpack("C#{width * 3}x#{line_remainder}")
  bytes.each_slice(3) { |b, g, r| pixels << ChunkyPNG::Color.rgb(r, g, b) }
end

image = ChunkyPNG::Image.new(width, height, pixels)
image.flip_horizontally!

image.save('converted_from_bmp.png')