Skip to content

Instantly share code, notes, and snippets.

@bmarini
Created February 3, 2010 16:06
Show Gist options
  • Save bmarini/293713 to your computer and use it in GitHub Desktop.
Save bmarini/293713 to your computer and use it in GitHub Desktop.
module Bitmap
def self.bgr_to_rgba(raw_bgr_array, width, height, new_dimension)
width_padding = new_dimension - width
height_padding = new_dimension - height
# First convert to array of Pixel::BGR objects
raw_bgr_array.enum_for(:each_slice, 3).map { |a| Pixel::BGR.new(*a) }.
reverse. # Reverse it
map { |bgr| bgr.to_rgba }. # Map to array of Pixel::RGBA objects
enum_for(:each_slice, width).inject([]) { |memo, row| memo << row }. # Create a 2d array based on width
map { |row|
row.concat( [Pixel::RGBA.blank] * width_padding )
}.concat( [ [Pixel::RGBA.blank] * new_dimension ] * height_padding ). # Change dimensions of 2d array, adding blanks
flatten.map { |rgba| rgba.to_a }.flatten # Flatten everything back into an array of integers
end
module Pixel
class RGBA < Struct.new(:red, :green, :blue, :alpha)
def self.blank
new(0,0,0,0)
end
def to_a
[red, green, blue, alpha]
end
end
class BGR < Struct.new(:blue, :green, :red)
def to_rgba
RGBA.new(red, green, blue, 255)
end
end
end
end
if __FILE__ == $0
require "test/unit"
class TestBgrToRgba < Test::Unit::TestCase
def test_bgr_to_rgba
width = 2
height = 3
real_size = 4 # closest power of 2
data = [
255, 0, 0, # 1st pixel, blue (third row)
255, 0, 0, # 2st pixel, blue
0, 255, 0, # 3nd pixel, green (second row)
0, 255, 0, # 4nd pixel, green
0, 0, 255, # 5rd pixel, red (first row)
0, 0, 255, # 6rd pixel, red
]
corrected = [
255, 0, 0, 255, # 1st pixel, red (first row)
255, 0, 0, 255, # 2st pixel, red
0, 0, 0, 0, # Empty
0, 0, 0, 0, # Empty
0, 255, 0, 255, # 3nd pixel, green (second row)
0, 255, 0, 255, # 4nd pixel, green
0, 0, 0, 0, # Empty
0, 0, 0, 0, # Empty
0, 0, 255, 255, # 5rd pixel, blue (third row)
0, 0, 255, 255, # 6rd pixel, blue
0, 0, 0, 0, # Empty
0, 0, 0, 0, # Empty
0, 0, 0, 0, # Empty (last row)
0, 0, 0, 0, # Empty
0, 0, 0, 0, # Empty
0, 0, 0, 0 # Empty
]
result = Bitmap.bgr_to_rgba(data, width, height, real_size)
assert_equal corrected, result
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment