开发者

(J)Ruby: different results of [].pack('m') using Jruby or Ruby

开发者 https://www.devze.com 2023-02-15 01:05 出处:网络
I want to encode a jpeg image to base64. Googling, i have this code: name = \'path_to_file\' b64 = [open(name).read].pack(\'m\')

I want to encode a jpeg image to base64. Googling, i have this code:

name = 'path_to_file'
b64 = [open(name).read].pack('m')
puts b64.size

If this code its executed with Jruby1.5.1 (come with netbeans), the result of the size(with my image) its 3518, but if its executed with ruby 1.8.7, the size its 90. Passing to an html file, only the enco开发者_开发知识库ded with JRuby works.

Someone know the reason of this? Thanks in advance. Notes: Running in Windows, and i hasn't touched the ruby1.8.7 code.


Windows has different behaviour depending upon whether you open the file in binary mode or not; change that line to:

b64 = [open(name, 'rb').read].pack('m')


I am getting the same sizes in jruby 1.5.1 RVM on Linux and Ruby 1.8.7 on Linux. I suspect that you are only encoding the path for some reason. Try printing open(name).read and assure your file is being opened and read successfully. I do not think that it is.

jruby-1.5.1 :001 >  [open("test.jpg").read].pack('m').size
 => 3274 

ruby-1.8.7-p302 :003 > [open("test.jpg").read].pack('m').size
 => 3274 
0

精彩评论

暂无评论...
验证码 换一张
取 消