Module: Phantoshot

Includes:
MiniMagick
Defined in:
lib/phantoshot.rb,
lib/phantoshot/version.rb,
lib/phantoshot/make_screenshot.rb

Constant Summary collapse

JS_LIB_NAME =
File.join(File.dirname(__FILE__), "/phantom-shot-script.js")
VERSION =
"0.0.6"

Instance Method Summary collapse

Instance Method Details

#make_screenshot(url, opts = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/phantoshot/make_screenshot.rb', line 5

def make_screenshot(url, opts={})

   desired_width = opts[:width]
   desired_height = opts[:height]

   res = MultiJson.load( 
      phantom_command(url)
   )

   hsh = Hashie::Mash.new(res)

   # Decode it for writing out to binary
   hsh[:image_data] = Base64.decode64( hsh[:image_data] )   

   tempfile = Tempfile.new('foo.png')
   tempfile.binmode

   tempfile.write(hsh[:image_data])
   tempfile.close

   img = MiniMagick::Image.open(tempfile.path)


   if desired_width && desired_width < img[:width]
      img.resize(desired_width)
   end

   if !desired_height.nil? && desired_height < img[:height]
      img.crop("#{img[:width]}x#{desired_height}+0+0")
   end

   tempfile2 = Tempfile.new('bar.png')
   tempfile2.binmode

   img.write(tempfile2.path)

   tempfile2.close

   hsh[:width] = img[:width]
   hsh[:height] = img[:height]
   hsh[:image_data] = open(tempfile2.path){ |f| f.read }
   return hsh
end

#phantom_command(url) ⇒ Object

returns JSON string with these attributes: :image_data (in base64), :file_format (default is PNG), and :url



53
54
55
56
# File 'lib/phantoshot/make_screenshot.rb', line 53

def phantom_command(url)
   cmd = "phantomjs #{JS_LIB_NAME} #{url}"
   `#{cmd}`
end