Not logged inGosu Forums
Forum back to libgosu.org Help Search Register Login
Up Topic Gosu / Gosu Exchange / Replacing an image's colours in pure Ruby: Image#silhouette
- By jlnr (dev) Date 2013-01-06 02:04
dspencer just asked about a way to make an image white in #gosu - and even though Texplay is the right library for this job, I couldn't resist doing it in pure Ruby :) This snippet illustrates how to perform simple operations on an image by using binary regular expressions. Using a Ruby loop for this would be much slower.

I am not sure if this snippet is slower or faster than Texplay, though it shoul be fast enough for most purposes. But unlike Texplay (in its current version), it should also work with very large images.

Tested in Ruby 1.8.7 and 1.9.3. Note that this method creates a new image and leaves the original image intact.

class Gosu::Image
  def silhouette(window, color, tileable=false)
    # Ensure that color is really a color - not a AARRGGBB integer
    color = Gosu::Color.argb(color) if not color.is_a? Gosu::Color
    # Convert image to binary string
    binary_data = self.to_blob
    # Run a regex on this binary string - the /n option makes it binary, and the
    # /m option additionally ensures that line-breaks are ignored
    # This regex replaces the 'rgb' bytes in each 'rgba' quad by the rgb values
    # from the given color.
    binary_data.gsub! /...(.)/nm,
                      "#{color.red.chr}#{color.green.chr}#{color.blue.chr}\\1"
    # Create a small wrapper that has the same interface as RMagick::Image
    binary_string_adapter = Struct.new(:columns, :rows, :to_blob)
    adapter = binary_string_adapter.new(self.width, self.height, binary_data)
    # Tada - there's the new image
    Gosu::Image.new(window, adapter, tileable)
  end
end
Attachment: Tutorial.rb - modified tutorial that uses #silhouette (4k)
Up Topic Gosu / Gosu Exchange / Replacing an image's colours in pure Ruby: Image#silhouette

Powered by mwForum 2.29.7 © 1999-2015 Markus Wichitill