Skip to content

Instantly share code, notes, and snippets.

@PRotondo
Created April 21, 2013 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PRotondo/5430419 to your computer and use it in GitHub Desktop.
Save PRotondo/5430419 to your computer and use it in GitHub Desktop.
PNG: from colour to black-and-white.
require 'cairo'
#input and output come as arguments
input, output = ARGV
surface = Cairo::ImageSurface.from_png input
goal_data = surface.data
HEIGHT, WIDTH = surface.height, surface.width
o_surface = Cairo::ImageSurface.new(WIDTH, HEIGHT)
cr = Cairo::Context.new(o_surface)
(0..WIDTH-1).each do |x|
(0..HEIGHT-1).each do |y|
this_pixel = y * WIDTH * 4 + x * 4
blue = goal_data[this_pixel].ord
red = goal_data[this_pixel+2].ord
green= goal_data[this_pixel+1].ord
avg = (blue+red+green)/ 765.0
cr.rectangle(x,y,1,1)
cr.set_source_rgb(avg,avg,avg)
cr.fill
end
end
o_surface.write_to_png output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment