Skip to content

Instantly share code, notes, and snippets.

@petewarden
Created November 28, 2011 02:44
Show Gist options
  • Save petewarden/1398869 to your computer and use it in GitHub Desktop.
Save petewarden/1398869 to your computer and use it in GitHub Desktop.
An example of using PhantomJS from Ruby to do server-side rendering of a web page into a PNG
require 'rubygems' if RUBY_VERSION < '1.9'
require 'tempfile'
require File.join(ENV['JETPAC_PATH'], 'library/logger')
require File.join(ENV['JETPAC_PATH'], 'library/email')
def image_command(command)
log "IMG: Running '#{command}'"
result = system(command)
if !result
error_message = "image_command() failed with code #{$?}: '#{command}'"
send_report_email('Image error', error_message)
raise error_message
end
end
def webpage2image(url, cookies)
output_data = nil
begin
cookies_file = Tempfile.new('webpage2image_cookies')
cookies.each do |domain, domain_cookies|
cookies_file.puts("[#{domain}]")
domain_cookies.each do |name, value|
value.gsub!(/\n/, "")
cookies_file.puts("#{name}=#{value}")
end
end
cookies_file.close
# Looks weird, but this reserves a guaranteed-unique filename for the output
output_file = Tempfile.new('webpage2image_output')
output_file.close
output_file_path = output_file.path+'.png'
command = 'xvfb-run --server-args="-screen 0, 1280x960x24" '
command += File.join(ENV['PHANTOMJS_PATH'], 'bin/phantomjs')+' '
command += '--cookies-file='+cookies_file.path+' '
command += File.join(ENV['PHANTOMJS_PATH'], 'examples/rasterize.js')+' '
command += url+' '
command += output_file_path+' '
image_command(command)
result_file = File.open(output_file_path, 'rb')
output_data = result_file.read
result_file.close
rescue Exception => e
log "webpage2image exception: #{e}: #{e.message}"
raise e
ensure
# Delete the temporary files
if cookies_file then cookies_file.unlink end
if output_file then output_file.unlink end
if output_file_path then File.delete(output_file_path) end
end
output_data
end
if __FILE__ == $0
image_data = webpage2image('http://petewarden.typepad.com', {})
File.open('petewarden.png', 'w').write(image_data)
end
@9mm
Copy link

9mm commented May 15, 2012

This is what i seem to be looking for (generating image thumbnails in ruby). Could you perhaps help a bit on how to implement this?

@petewarden
Copy link
Author

petewarden commented May 16, 2012 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment