使用Ruby将png图像发布到pngcrush [英] Post png image to pngcrush with Ruby

查看:137
本文介绍了使用Ruby将png图像发布到pngcrush的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ruby中,我希望得到与下面的代码相同的结果,但不使用curl:

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}`

我试过这个:

#!/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."


推荐答案

您的代码存在的问题是您不需要发送服务器的参数( http://pngcrush.com/crush 的输入)。这对我有用:

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

但是我建议你使用 RestClient 。它将ne​​t / http与很酷的功能(如多部分表单数据)封装起来,只需要几行代码即可完成工作

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

用<$ c安装$ c> gem install rest-client

这篇关于使用Ruby将png图像发布到pngcrush的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆