Skip to content

Instantly share code, notes, and snippets.

@aalin
Last active December 14, 2015 18:29
Show Gist options
  • Select an option

  • Save aalin/5129639 to your computer and use it in GitHub Desktop.

Select an option

Save aalin/5129639 to your computer and use it in GitHub Desktop.
OpenGL screenshots with ChunkyPNG
# This takes about 1.6 seconds for 800x600
def short_screenshot!(width, height)
pixels = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE)
image = ChunkyPNG::Image.from_rgb_stream(width, height, StringIO.new(pixels))
image.flip_horizontally!
image.save('screenshot.png', :fast_rgb)
end
# This takes about 0.8 seconds for 800x600
def long_screenshot!(width, height)
pixels = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE).bytes.to_a
image = ChunkyPNG::Image.new(width, height)
width.times do |x|
height.times do |y|
color = pixels.slice((y * width + x) * 3, 3)
image[x, height.pred - y] = ChunkyPNG::Color.rgb(*color)
end
end
image.save('screenshot.png', :fast_rgb)
end
# This takes about 0.76 seconds, and of that, flipping is 0.6 seconds.
def new_screenshot!(width, height)
gl_pixels = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE)
File.open('pixels', 'w') { |f| f.write gl_pixels }
# Flip horizontally.
string = gl_pixels.bytes.each_slice(width * 3).to_a.reverse.flatten.map(&:chr).join
string << ChunkyPNG::EXTRA_BYTE # Add a fourth byte to the last RGB triple.
unpacker = 'NX' * (width * height)
pixels = string.unpack(unpacker).map { |color| color | 0x000000ff }
image = ChunkyPNG::Image.new(width, height, pixels)
image.save('screenshot.png', :fast_rgb)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment