Converting image to byte array in ruby

ruby, ruby-on-rails

Solution

Read as binary file and unpack it

f = File.binread 'image.png'    

f.unpack('B*')
# Outputs like ["0010010101110010000100110000010000010"] 

# Byte Array
# "abc".unpack('C*')
#=> [97, 98, 99]

f.unpack('C*')

Check here for the different `unpack` options

Problem

I have a png image as a paperclip attachment and I need to send it to a web service interface as a byte array. How to convert the image file to a byte array? There is an existing question How to convert image file to byte array using ruby but it is rather old and the only answer suggests using RMagick gem (no example code or anything). Is the RMagick gem really needed for accomplishing this? I wouldn't like to add a new gem without a good reason.

Original source