Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'msgpack'
require 'base64'
require 'awesome_print'
-> {
#
# Serialize Image
# - MessagePack
# - Base64
#
file = File.open("./../soup.jpeg", 'rb')
binary = file.read
file.close
obj = {
image: binary,
filename: 'soup.jpeg',
media_type: 'jpeg',
}
binary_size = binary.bytesize
ap "size(binary): #{binary_size} (-)"
msg = MessagePack.pack(obj)
msg_size = msg.bytesize
ap "size(msgpack): #{msg_size} (+#{(msg_size/binary_size.to_f).round(4)})"
base64_image = Base64.strict_encode64(binary)
base64_image_size = base64_image.bytesize
ap "size(base64): #{base64_image_size} (+#{(base64_image_size/binary_size.to_f).round(4)})"
# File.open("./tmp.jpeg", 'wb') do |f|
# f.write MessagePack.unpack(msg)['image']
# end
file.close
# => "size(binary): 5141 (-)"
# => "size(msgpack): 5186 (+1.0088)"
# => "size(base64): 6856 (+1.3336)"
}.call
__END__
https://github.com/msgpack/msgpack-ruby
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment