Skip to content

Instantly share code, notes, and snippets.

@msroz
Created December 6, 2018 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msroz/096b8708033c8dec00edd2cd4f7c162e to your computer and use it in GitHub Desktop.
Save msroz/096b8708033c8dec00edd2cd4f7c162e to your computer and use it in GitHub Desktop.
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