Using the Picnik API from Rails
The Picnik API makes it easy to add online image editing to any site that hosts images.
For the benefit of those coding in Rails, here's a summary of how I integrated Picnik with iLike to allow our users to touch up photos after upload.
I used the "pull version" of the API, which for our purposes was simplest and provided the most control. In a nutshell, you just need to link the user to the Piknik site with URL of the image to edit and some configuration parameters. When the user is done, Picnik links the user back to your site and passes the URL of the edited image back on the query string. Very simple!
(1) First, I constructed a helper to link the user to Picnik with the appropriate parameters.
In the code below, "image_url" is the URL of the image to edit on our site. "export_url" is the URL that Picnik links back to when the user is done editing. "export_parameter" is the parameter to use for passing back the edited URL. (Note the gotcha about encoding spaces as '%20' and not '+')
-
module ApplicationHelper
-
def picnik_edit_url(image_url, export_param, export_url)
-
host_name = 'YOURSITE'
-
params = {
-
:import => image_url,
-
:export => export_url,
-
:export_field => export_param,
-
:apikey => 'YOURAPIKEY',
-
:close_target => export_url,
-
:export_agent => 'browser',
-
:out_format => 'png',
-
:export_title => "Save and return to #{host_name}",
-
:exclude => 'in,create',
-
:host_name => host_name
-
}
-
"http://www.picnik.com/service/?#{escape_picnik_params(params)}"
-
end
-
def escape_picnik_params(params)
-
params.map { |k,v|
-
"_#{strict_escape(k)}=#{strict_escape(v)}"
-
}.join("&")
-
end
-
def strict_escape(s)
-
# escape spaces as %20; picnik won't accept +
-
CGI.escape(s.to_s).gsub("+", "%20")
-
end
-
end
2. Next I added links to edit images to our RHTML templates.
-
<%= link_to "Edit image",
-
picnik_edit_url(logo_url, 'logo_file', url_for(:only_path => false)) %>
3. Finally I customized our controller action to handle an edited image parameter:
-
require 'open-uri'
-
def settings_bannerphoto
-
if !params[:banner_file].blank?
-
image_file = open(params[:banner_file])
-
# do what you want with the image file (e.g. save it)
-
end
-
end
Quite simple, and we just repeat steps 2 and 3 to make additional images on our site editable.