Post png image to pngcrush with Ruby

533 views Asked by At

In ruby, I want to get the same result than the code below but 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 to crush
png_image_path = "./media/images/foo.png"

# Crush with 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 is empty, provide a PNG image."
1

There are 1 answers

2
Vitalii Elenhaupt On BEST ANSWER

The problem with your code is you do not send required parameter to the server ("input" for http://pngcrush.com/crush). This works for 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') do |file|
  file.write(response.body)
end

But I suggest you to use RestClient. It encapsulates net/http with cool features like multipart form data and you need just a few lines of code to do the job:

require 'rest_client'

resp = RestClient.post('http://pngcrush.com/crush',
  :input => File.new('filename.png'))

# save crushed image
open('crushed.png', 'wb') do |file|
  file.write(resp)
end

Install it with gem install rest-client