Skip to content

Instantly share code, notes, and snippets.

@Shinichi-Ohki
Last active December 16, 2015 04:19
Show Gist options
  • Save Shinichi-Ohki/5376430 to your computer and use it in GitHub Desktop.
Save Shinichi-Ohki/5376430 to your computer and use it in GitHub Desktop.
Bitmap file header remover (BMPファイルのヘッダを取ってテキストで出力する)
#!/usr/bin/env ruby
# encoding: utf-8
bmp_file = open(ARGV[0])
# Windowsの場合はバイナリファイルを扱う場合binmodeにしないと途中からデータがズレる
bmp_file.binmode
temp = bmp_file.read(2) # Check file type
if temp != 'BM'
puts 'Not BMP file'
exit
end
bmp_size = bmp_file.read(4).unpack('V') # Read file size
temp = bmp_file.read(4) # Drop reserved area
bmp_offset = bmp_file.read(4).unpack('V') # Read offset(from file head to picture data)
bmp_header_size = bmp_file.read(4).unpack('V') # Read header size
if bmp_header_size == 12
bmp_width = bmp_file.read(2).unpack('v')
bmp_height = bmp_file.read(2).unpack('v')
bmp_planes = bmp_file.read(2).unpack('v')
bmp_bit_count = bmp_file.read(2).unpack('v')
temp = bmp_file.read(bmp_offset[0] - 26)
else
bmp_width = bmp_file.read(4).unpack('V')
bmp_height = bmp_file.read(4).unpack('V')
bmp_planes = bmp_file.read(2).unpack('v')
bmp_bit_count = bmp_file.read(2).unpack('v')
temp = bmp_file.read(bmp_offset[0] - 30)
end
bmp_data = bmp_file.read(bmp_width[0] * bmp_height[0] * bmp_bit_count[0] / 8)
=begin
print("Size = %d byte(s)\n"%bmp_size) // For debug
print("Width = %d line(s)\n"%bmp_width)
print("Height = %d line(s)\n"%bmp_height)
print("Offset = %d byte(s)\n"%bmp_offset)
print("Data size = %d byte(s)\n"%bmp_data.size)
=end
lc = bmp_height[0] - 1
lc.downto(0) do |j|
(bmp_width[0] * bmp_bit_count[0] / 8).times do |i|
print '0x%s'%bmp_data[(j * (bmp_width[0] * bmp_bit_count[0] / 8)) + i].unpack('H*')
print ',' unless (j == 0) && (i == (bmp_width[0] * bmp_bit_count[0] / 8) - 1)
print "\n" if (i % 16) == 15
end
end
BMPファイルのヘッダを取って、テキストで出力します。
BMPファイルを引数として渡して実行します。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment