http - Post png image to pngcrush with Ruby -
in ruby, want same result code below without using curl:
curl_output = `curl -x post -s --form "input=@#{png_image_file};type=image/png" http://pngcrush.com/crush > #{compressed_png_file}`
i tried this:
#!/usr/bin/env ruby require "net/http" require "uri" # image crush png_image_path = "./media/images/foo.png" # crush http://pngcrush.com/ png_compress_uri = uri.parse("http://pngcrush.com/crush") png_image_data = file.read(png_image_path) req = net::http.new(png_compress_uri.host, png_compress_uri.port) headers = {"content-type" => "image/png" } response = req.post(png_compress_uri.path, png_image_data, headers) p response.body # => "input empty, provide png image."
the problem code not send required parameter server ("input" http://pngcrush.com/crush). works me:
require 'net/http' require 'uri' uri = uri.parse('http://pngcrush.com/crush') form_data = [ ['input', file.open('filename.png')] ] http = net::http.new(uri.host, uri.port) request = net::http::post.new uri # prepare request parameters request.set_form(form_data, 'multipart/form-data') response = http.request(request) # save crushed image open('crushed.png', 'wb') |file| file.write(response.body) end
but suggest use restclient. encapsulates net/http cool features multipart form data , need few lines of code job:
require 'rest_client' resp = restclient.post('http://pngcrush.com/crush', :input => file.new('filename.png')) # save crushed image open('crushed.png', 'wb') |file| file.write(resp) end
install gem install rest-client
Comments
Post a Comment