Permalink
Browse files

add an example worker and client for scaling images

git-svn-id: http://code.sixapart.com/svn/gearman/trunk/api/ruby@282 011c6a6d-750f-0410-a5f6-93fdcd050bc4
  • Loading branch information...
1 parent ab83a86 commit 7a49565bcdad0caeba5cfeabb73ae785e55ac8f8 derat committed May 12, 2007
Showing with 68 additions and 0 deletions.
  1. +33 −0 examples/scale_image.rb
  2. +35 −0 examples/scale_image_worker.rb
View
33 examples/scale_image.rb
@@ -0,0 +1,33 @@
+#!/usr/bin/ruby
+
+$: << '../lib'
+require 'base64'
+require 'gearman'
+require 'optparse'
+
+Gearman::Util.debug = true
+servers = 'localhost:7003'
+format = 'PNG'
+width, height = 100, 100
+
+opts = OptionParser.new
+opts.banner = "Usage: #{$0} [options] <input> <output>"
+opts.on('-f FORMAT', '--format', 'Scaled image format') { format }
+opts.on('-h HEIGHT', '--height', 'Scaled image height') { height }
+opts.on('-s SERVERS', '--servers',
+ 'Servers, comma-separated host:port') { servers }
+opts.on('-w WIDTH', '--width', 'Scaled image width') { width }
+opts.parse!
+
+if ARGV.size != 2
+ $stderr.puts opts.banner
+ exit 1
+end
+
+client = Gearman::Client.new(servers.split(','), 'example')
+taskset = Gearman::TaskSet.new(client)
+arg = [width, height, format, Base64.encode64(File.read(ARGV[0]))].join("\0")
+task = Gearman::Task.new('scale_image', arg)
+task.on_complete {|d| File.new(ARGV[1],'w').write(Base64.decode64(d)) }
+taskset.add_task(task)
+taskset.wait(10)
View
35 examples/scale_image_worker.rb
@@ -0,0 +1,35 @@
+#!/usr/bin/ruby
+
+$: << '../lib'
+require 'base64'
+require 'gearman'
+require 'optparse'
+require 'RMagick'
+
+Gearman::Util.debug = true
+servers = 'localhost:7003'
+
+opts = OptionParser.new
+opts.banner = "Usage: #{$0} [options]"
+opts.on('-s SERVERS', '--servers', 'Job servers,
+ comma-separated host:port') { servers }
+opts.parse!
+
+worker = Gearman::Worker.new(servers.split(','), 'example')
+
+worker.add_ability('scale_image') do |data,job|
+ width, height, format, data = data.split("\0", 4)
+ width = width.to_f
+ height = height.to_f
+ image = Magick::Image.from_blob(Base64.decode64(data))[0]
+ orig_ratio = image.columns.to_f / image.rows
+ new_ratio = width / height
+ w = new_ratio < orig_ratio ? width : orig_ratio / new_ratio * width
+ h = new_ratio > orig_ratio ? height : new_ratio / orig_ratio * height
+ puts "Got #{image.inspect}; resizing to #{w}x#{h} #{format}"
+ image.resize!(w, h)
+ image.format = format
+ Base64.encode64(image.to_blob)
+end
+
+loop { worker.work }

0 comments on commit 7a49565

Please sign in to comment.