我正在使用名为rubypress的gem来使用XMLRPC将ruby中的内容发布到wordpress。除图像上传部分外,一切正常。我将图像转换为base64编码格式,但在上传后,我得到的只是灰色图像,而不是我打算上传的图像(我使用大约100kb大小的较小图像上传进行测试)。我做错了什么? 以下是来自rubypress github页面(https://github.com/zachfeldman/rubypress)的代码,用于上传:
FILENAME='myFile.png'
wp.uploadFile(:data => {
:name => FILENAME,
:type => MIME::Types.type_for(FILENAME).first.to_s,
:bits => XMLRPC::Base64.new(IO.read(FILENAME))
})
答案 0 :(得分:0)
尝试:
wp.uploadFile(:data => {:name => File.basename(FILENAME),
:type => MIME::Types.type_for(FILENAME).first.to_s,
:bits => XMLRPC::Base64.new(File.open(FILENAME).read)
})
答案 1 :(得分:0)
我终于能够通过更改Base64编码代码来解决它:
$wp.uploadFile(:data => {
:name => File.basename(imgname),
:type => MIME::Types.type_for(imgname).first.to_s,
:bits => XMLRPC::Base64.new(File.open(FILENAME,"rb").read),
:post_id =>postid
})
该文件显然需要首先“打开”,而不是使用IO.read(FILENAME)读取。
答案 2 :(得分:0)
这是我的做法,效果很好:
image = MiniMagick::Image.open(this_image.path)
image.format('jpg')
image.combine_options do |c|
c.strip
end
image.write(this_image.path)
# most efficient resize as suggested by https://www.smashingmagazine.com/2015/06/efficient-image-resizing-with-imagemagick/
MiniMagick::Tool::Mogrify.new do |mogrify|
mogrify.filter('Triangle')
mogrify.define('filter:support=2')
mogrify.thumbnail('960x')
mogrify.unsharp('0.25x0.08+8.3+0.045')
mogrify.dither('None')
mogrify.posterize('136')
mogrify.quality('82')
mogrify.define('jpeg:fancy-upsampling=off')
mogrify.interlace('none')
mogrify.colorspace('sRGB')
mogrify << this_image.path
end
type = image.mime_type
bits = XMLRPC::Base64.new(IO.read(this_image.path))
begin
result = wp.uploadFile(
data: {
name: image_name,
type: type,
bits: bits,
post_id: post_id,
overwrite: true
})
rescue StandardError => e
puts e
end