Created
August 18, 2010 22:59
-
-
Save wvanbergen/536467 to your computer and use it in GitHub Desktop.
Create PNG from 24 bit BMP file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.save('filename.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment